UNPKG

@itrocks/mysql-maintainer

Version:

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

71 lines 2.68 kB
import { typeOf } from '@itrocks/class-type'; import { MysqlToTable } from '@itrocks/mysql-to-schema'; import { ReflectToTable } from '@itrocks/reflect-to-schema'; import { TableDiff } from '@itrocks/schema-diff'; import { SchemaDiffMysql } from '@itrocks/schema-diff-mysql'; import { storeOf } from '@itrocks/store'; export * from './mysql'; export class MysqlMaintainer { connection; constructor(connection) { this.connection = connection; } createContextTables(context) { const contexts = Array.isArray(context) ? context : [context]; for (const context of contexts) { this.createTable(typeOf(context)); } return false; } createImplicitTables(sql) { return false; } createTable(type) { return false; } async manageError(error, context, sql, values) { console.log('query', sql, values); console.log('throw', error); console.log('context', context); switch (error.code) { case 'ER_BAD_FIELD_ERROR': case 'ER_CANNOT_ADD_FOREIGN': return await this.updateContextTables(context); case 'ER_CANT_CREATE_TABLE': return this.createImplicitTables(sql); case 'ER_NO_SUCH_TABLE': return this.createContextTables(context); } return false; } async updateContextTables(context) { const contexts = Array.isArray(context) ? context : [context]; for (const context of contexts) { await this.updateTable(typeOf(context)); } return false; } async updateTable(type) { const tableName = storeOf(type); if (!tableName) { throw 'No table name for type'; } console.log('##### UPDATE TABLE'); console.log('class table before normalize:'); const classTable = new ReflectToTable().convert(type); console.dir(classTable, { depth: null }); console.log('class table after normalize:'); new MysqlToTable(this.connection).normalize(classTable); console.dir(classTable, { depth: null }); console.log('mysql table:'); const mysqlTable = await ((new MysqlToTable(this.connection)).convert(tableName)); console.dir(mysqlTable, { depth: null }); console.log('table diff:'); const schemaDiff = new TableDiff(mysqlTable, classTable); console.dir(schemaDiff, { depth: null }); const schemaDiffMysql = new SchemaDiffMysql(); console.log(schemaDiffMysql.sql(schemaDiff, true)); return false; } } //# sourceMappingURL=mysql-maintainer.js.map