-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread.js
More file actions
95 lines (86 loc) · 2.17 KB
/
Copy paththread.js
File metadata and controls
95 lines (86 loc) · 2.17 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const Table = require('./table');
const getConnection = Symbol('mysql:thread:getConnection');
module.exports = class Thread {
constructor(mysql) {
this.conn = null;
this.lifes = {};
this.mysql = mysql;
this.init();
}
on(name, callback) {
if (!this.lifes[name]) this.lifes[name] = [];
this.lifes[name].push(callback);
return this;
}
async emit(name, ...args) {
if (this.lifes[name]) {
const life = this.lifes[name];
for (let i = 0; i < life.length; i++) {
await life[i](...args);
}
}
}
init() {
for (const table in this.mysql.tables) {
this[table] = new Table(this, table, this.mysql.tables[table]);
}
}
async exec(sql, ...args) {
await this.getConn();
await this.emit('beforeExec', sql, ...args);
const res = await new Promise((resolve, reject) => {
this.conn.query(sql, args, (err, rows) => {
if (err) return reject(err);
resolve(rows);
});
});
await this.emit('exec', res);
return res;
}
async getConn() {
if (this.conn) return this.conn;
if (this.mysql.mode === 'pool') return this.conn = await this.mysql.getConnection();
return this.conn = this.mysql.dbo;
}
release() {
if (this.mysql.mode === 'pool' && this.conn) {
this.conn.release();
}
this.conn = null;
}
async begin() {
await this.getConn();
await this.emit('beforeBegin');
await new Promise((resolve, reject) => {
this.conn.beginTransaction(err => {
if (err) return reject(err);
resolve();
})
});
await this.emit('begin');
}
async commit() {
if (!this.conn) return;
await this.emit('beforeCommit');
await new Promise((resolve, reject) => {
this.conn.commit(err => {
if (err) return reject(err);
resolve();
})
});
this.release();
await this.emit('commit');
}
async rollback() {
if (!this.conn) return;
await this.emit('beforeRollback');
await new Promise((resolve, reject) => {
this.conn.rollback(err => {
if (err) return reject(err);
resolve();
})
});
this.release();
await this.emit('rollback');
}
}