UNPKG

zumito-db

Version:

Multi-driver database abstraction layer with decorator-based models

47 lines (46 loc) 1.62 kB
export class MigrationRunner { db; migrationsTable = '_zumito_migrations'; constructor(db) { this.db = db; } async ensureMigrationsTable() { const driver = this.db.getDriver(); const metadata = { name: 'MigrationRecord', collection: this.migrationsTable, fields: [ { name: 'name', type: 'string', primary: true, unique: true, nullable: false, propertyKey: 'name' }, { name: 'executed_at', type: 'string', primary: false, unique: false, nullable: false, propertyKey: 'executedAt' }, ], relations: [], target: null, }; await driver.ensureSchema(metadata); } async getExecuted() { const driver = this.db.getDriver(); const results = await driver.find(this.migrationsTable, { collection: this.migrationsTable, type: 'find', where: [], }); return results.map((r) => r.name); } async runUp(migration) { await this.ensureMigrationsTable(); await migration.up(this.db); await this.db.getDriver().insert(this.migrationsTable, { name: migration.name, executed_at: new Date().toISOString(), }); } async runDown(migration) { await migration.down(this.db); await this.db.getDriver().delete(this.migrationsTable, { collection: this.migrationsTable, type: 'delete', where: [{ field: 'name', operator: 'eq', value: migration.name, logic: 'and' }], }); } }