oak-db/lib/MySQL/connector.js

78 lines
2.6 KiB
JavaScript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MySqlConnector = void 0;
const tslib_1 = require("tslib");
const promise_1 = tslib_1.__importDefault(require("mysql2/promise"));
const uuid_1 = require("uuid");
const assert_1 = tslib_1.__importDefault(require("assert"));
class MySqlConnector {
pool;
configuration;
txnDict;
constructor(configuration) {
this.configuration = configuration;
this.txnDict = {};
this.pool = promise_1.default.createPool(this.configuration);
}
connect() {
}
disconnect() {
return this.pool.end();
}
async startTransaction(option) {
// 防止用户配置connection可复用
const startInner = async () => {
const connection = await this.pool.getConnection();
// 分配出来的connection不能被别的事务占据
for (const txn2 in this.txnDict) {
if (this.txnDict[txn2] === connection) {
return new Promise((resolve) => {
this.pool.on('release', () => resolve(startInner()));
});
}
}
await connection.beginTransaction();
const id = (0, uuid_1.v4)();
// console.log('start_txn', id, connection.threadId);
this.txnDict[id] = connection;
if (option?.isolationLevel) {
await connection.query(`SET TRANSACTION ISOLATION LEVEL ${option.isolationLevel};`);
}
return id;
};
return startInner();
}
async exec(sql, txn) {
if (process.env.NODE_ENV === 'development') {
// console.log(`${sql}; \n`);
}
if (txn) {
const connection = this.txnDict[txn];
(0, assert_1.default)(connection);
const result = await connection.query(sql);
return result;
}
else {
const result = await this.pool.query(sql);
return result;
}
}
async commitTransaction(txn) {
const connection = this.txnDict[txn];
(0, assert_1.default)(connection);
delete this.txnDict[txn];
// console.log('commit_txn', txn, connection.threadId);
await connection.commit();
connection.release();
}
async rollbackTransaction(txn) {
const connection = this.txnDict[txn];
(0, assert_1.default)(connection);
// console.log('rollback_txn', txn, connection.threadId);
await connection.rollback();
delete this.txnDict[txn];
connection.release();
}
}
exports.MySqlConnector = MySqlConnector;