import mysql = require("mysql"); import sleep from "sleep-es6"; import getColumns from "./util/columns"; import { getFieldsFromList, prepareValue } from "./util/insert"; export type IDBConfig = mysql.IConnectionConfig & { logging?: boolean; }; class DB { public connection: mysql.IConnection; constructor(protected config: IDBConfig) { this.connect(); } public async close() { await new Promise((resolve, reject) => { this.connection.end((err) => { if (err) { reject(err); } resolve(); }); }); } public query(sql: string, values?: any[]) { values = values || []; return new Promise((resolve, reject) => { const query = this.connection.query(sql, values, (err: any, results: any) => { if (err) { reject(err); return; } resolve(results); }); if (this.config.logging) { this.log(query.sql); } }); } public async insert(tableName: string, rows: any[], opts: { ignoreDuplicate?: boolean; onDuplicateKeyUpdateAll?: boolean; ignoreNullableValues?: boolean; } = { ignoreDuplicate: false, onDuplicateKeyUpdateAll: false, ignoreNullableValues: false }) { let schemaName: string; if (!this.config.database) { const p = tableName.split("."); if (p.length === 1) { throw new Error("Schema should be setted"); } schemaName = p[0]; tableName = p[1]; } else { schemaName = this.config.database; } const columns = await getColumns(this)(schemaName, tableName); const fields = getFieldsFromList(rows, columns); const forInserting = rows.map((row) => { const cols = []; for (const fieldName in fields) { if (typeof (row[fieldName]) === "undefined" || row[fieldName] === null) { if (!fields[fieldName].isNullable && !opts.ignoreNullableValues) { throw new Error("Empty value for non-nullable field " + fieldName); } cols.push(null); } else { cols.push(prepareValue(row[fieldName], fields[fieldName].type, fieldName, row)); } } return cols; }); const fieldsNames = Object.keys(fields); return this.query( `insert${opts.ignoreDuplicate ? " ignore" : ""} into ` + tableName + "(`" + fieldsNames.join("`,`") + "`) values ?" + (opts.onDuplicateKeyUpdateAll ? ` on duplicate key update ` + fieldsNames.map((name) => "`" + name + "` = VALUES(`" + name + "`)").join(", ") : ""), [forInserting], ); } public async beginTransaction() { return new Promise((resolve, reject) => { this.connection.beginTransaction((err: any) => { if (err) { reject(err); return; } resolve(); }); }); } public async commit() { return new Promise((resolve, reject) => { this.connection.commit((err: any) => { if (err) { reject(err); return; } resolve(); }); }); } public async rollback() { return new Promise((resolve) => { this.connection.rollback(() => { resolve(); }); }); } protected log(...args: any[]) { console.log.apply(console, args); } protected async connect() { this.connection = mysql.createConnection(this.config); this.connection.connect(async (err) => { if (err) { this.log("Connection error:", err); await sleep(1000); this.connect(); return; } }); this.connection.on("error", async (err) => { this.log("Connection error:", err); await sleep(1000); this.connect(); }); } } export default DB;