UNPKG

@itrocks/mysql-maintainer

Version:

Reactively maintains database structure by updating schema and retrying on MySQL errors

59 lines 2.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Contextual = void 0; const mysql_maintainer_1 = require("./mysql-maintainer"); const mysql_maintainer_2 = require("./mysql-maintainer"); const MANAGED_ERROR_CODES = ['ER_BAD_FIELD_ERROR', 'ER_CANNOT_ADD_FOREIGN', 'ER_NO_SUCH_TABLE']; class Contextual { contexts = []; errorCount = {}; superQuery = () => new Promise(() => { }); async applyTo(connection) { connection.contexts = []; connection.errorCount = {}; connection.incrementErrorCount = Contextual.prototype.incrementErrorCount; connection.isSqlError = Contextual.prototype.isSqlError; connection.superQuery = connection.query; connection.query = Contextual.prototype.query; return connection; } incrementErrorCount(sql, error) { if (!this.errorCount[sql]) { this.errorCount[sql] = {}; } if (!this.errorCount[sql][error.message]) { this.errorCount[sql][error.message] = []; } this.errorCount[sql][error.message].push(new Date().getTime()); console.log('incremented', this.errorCount[sql][error.message].length, ':', sql, error.message); return true; } isSqlError(error) { return (typeof error === 'object') && !!error.code; } async query(sql, values) { try { if (mysql_maintainer_1.DEBUG) console.log(sql, values); return await this.superQuery(sql, values); } catch (error) { if (!this.isSqlError(error) || !MANAGED_ERROR_CODES.includes(error.code)) { if (mysql_maintainer_1.DEBUG) console.log('MAINTAINER: throw', error); throw error; } sql = (typeof sql === 'object') ? sql.sql : sql; if (this.incrementErrorCount(sql, error) && (this.errorCount[sql][error.message].length < 5) && await new mysql_maintainer_2.MysqlMaintainer(this).manageError(error, this.contexts[this.contexts.length - 1], sql, values)) { return this.query(sql, values); } if (mysql_maintainer_1.DEBUG) console.log('MAINTAINER: throw (2)', error); throw error; } } } exports.Contextual = Contextual; //# sourceMappingURL=contextual-connection.js.map