forked from ChristopherBThai/Discord-OwO-Bot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mysqlHandler.js
76 lines (70 loc) · 1.76 KB
/
mysqlHandler.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
/*
* OwO Bot for Discord
* Copyright (C) 2019 Christopher Thai
* This software is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
* For more information, see README.md and LICENSE
*/
let con = require('../utils/mysql.js').con;
const acquireTimeLimit = 10000;
/* Converts mysql queries to Promises */
exports.query = function (sql, variables = []) {
return new Promise((resolve, reject) => {
con.query(sql, variables, function (err, rows) {
if (err) return reject(err);
resolve(rows);
});
});
};
exports.startTransaction = () => {
return new Promise((res, rej) => {
con.getConnection((err, acon) => {
if (err) return rej(err);
acon.beginTransaction((err) => {
if (err) throw err;
});
const result = {
commit: () => {
delete result.commit;
delete result.rollback;
delete result.query;
clearTimeout(releaseTimer);
return new Promise((res, rej) => {
acon.commit((err) => {
if (err)
return acon.rollback(() => {
rej(err);
});
acon.release();
res();
});
});
},
rollback: () => {
delete result.commit;
delete result.rollback;
delete result.query;
clearTimeout(releaseTimer);
return new Promise((res) => {
acon.rollback(() => {
acon.release();
res();
});
});
},
query: (sql, variables = []) => {
return new Promise((res2, rej2) => {
acon.query(sql, variables, (err, rows) => {
if (err) return rej2(err);
res2(rows);
});
});
},
};
let releaseTimer = setTimeout(() => {
console.error(`[${acon.threadId}] Mysql connection was not released!`);
result.rollback();
}, acquireTimeLimit);
res(result);
});
});
};