swaf/dist/db/MysqlConnectionManager.js

168 lines
22 KiB
JavaScript
Raw Normal View History

2020-04-22 15:52:17 +02:00
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import mysql from 'mysql';
import config from 'config';
import Logger from "../Logger";
export function query(queryString, values, connection) {
return __awaiter(this, void 0, void 0, function* () {
return yield MysqlConnectionManager.query(queryString, values, connection);
});
}
export default class MysqlConnectionManager {
static registerMigration(migration) {
this.migrations.push(migration(this.migrations.length + 1));
}
static prepare() {
return __awaiter(this, void 0, void 0, function* () {
if (config.get('mysql.create_database_automatically') === true) {
const dbName = config.get('mysql.database');
Logger.info(`Creating database ${dbName}...`);
const connection = mysql.createConnection({
host: config.get('mysql.host'),
user: config.get('mysql.user'),
password: config.get('mysql.password'),
});
yield new Promise((resolve, reject) => {
connection.query(`CREATE DATABASE IF NOT EXISTS ${dbName}`, (error) => {
if (error !== null) {
reject(error);
}
else {
resolve();
}
});
});
connection.end();
Logger.info(`Database ${dbName} created!`);
}
this.databaseReady = true;
yield this.handleMigrations();
});
}
static get pool() {
if (this.currentPool === undefined) {
this.currentPool = this.createPool();
}
return this.currentPool;
}
static createPool() {
return mysql.createPool({
connectionLimit: config.get('mysql.connectionLimit'),
host: config.get('mysql.host'),
user: config.get('mysql.user'),
password: config.get('mysql.password'),
database: config.get('mysql.database'),
});
}
static endPool() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise(resolve => {
if (this.currentPool !== undefined) {
this.currentPool.end(() => {
Logger.info('Mysql connection pool ended.');
resolve();
});
this.currentPool = undefined;
}
else {
resolve();
}
});
});
}
static query(queryString, values, connection) {
return __awaiter(this, void 0, void 0, function* () {
return yield new Promise((resolve, reject) => {
Logger.dev('Mysql query:', queryString, '; values:', values);
(connection ? connection : this.pool).query(queryString, values, (error, results, fields) => {
if (error !== null) {
reject(error);
return;
}
resolve({
results: Array.isArray(results) ? results : [],
fields: fields !== undefined ? fields : [],
other: Array.isArray(results) ? null : results
});
});
});
});
}
static wrapTransaction(transaction) {
return __awaiter(this, void 0, void 0, function* () {
return yield new Promise((resolve, reject) => {
this.pool.getConnection((err, connection) => {
if (err) {
reject(err);
return;
}
connection.beginTransaction((err) => {
if (err) {
reject(err);
this.pool.releaseConnection(connection);
return;
}
transaction(connection).then(val => {
connection.commit((err) => {
if (err) {
this.rejectAndRollback(connection, err, reject);
this.pool.releaseConnection(connection);
return;
}
this.pool.releaseConnection(connection);
resolve(val);
});
}).catch(err => {
this.rejectAndRollback(connection, err, reject);
this.pool.releaseConnection(connection);
});
});
});
});
});
}
static rejectAndRollback(connection, err, reject) {
connection.rollback((rollbackErr) => {
if (rollbackErr) {
reject(err + '\n' + rollbackErr);
}
else {
reject(err);
}
});
}
static handleMigrations() {
return __awaiter(this, void 0, void 0, function* () {
let currentVersion = 0;
try {
const result = yield query('SELECT id FROM migrations ORDER BY id DESC LIMIT 1');
currentVersion = result.results[0].id;
}
catch (e) {
if (e.code === 'ECONNREFUSED' || e.code !== 'ER_NO_SUCH_TABLE') {
throw new Error('Cannot run migrations: ' + e.code);
}
}
for (const migration of this.migrations) {
if (yield migration.shouldRun(currentVersion)) {
Logger.info('Running migration ', migration.version, migration.constructor.name);
yield migration.install();
yield query('INSERT INTO migrations VALUES(?, ?, NOW())', [
migration.version,
migration.constructor.name,
]);
}
}
});
}
}
MysqlConnectionManager.databaseReady = false;
MysqlConnectionManager.migrations = [];
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiTXlzcWxDb25uZWN0aW9uTWFuYWdlci5qcyIsInNvdXJjZVJvb3Q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