swaf/src/db/Migration.ts

41 lines
1.2 KiB
TypeScript
Raw Normal View History

2020-06-04 17:27:05 +02:00
import {Connection} from "mysql";
import {Type} from "../Utils.js";
import MysqlConnectionManager from "./MysqlConnectionManager.js";
2020-06-04 17:27:05 +02:00
2020-04-22 15:52:17 +02:00
export default abstract class Migration {
public readonly version: number;
private currentConnection?: Connection;
2020-04-22 15:52:17 +02:00
2020-07-24 12:13:28 +02:00
public constructor(version: number) {
2020-04-22 15:52:17 +02:00
this.version = version;
}
2020-07-24 12:13:28 +02:00
public async shouldRun(currentVersion: number): Promise<boolean> {
2020-04-22 15:52:17 +02:00
return this.version > currentVersion;
}
public abstract install(): Promise<void>;
2020-06-04 17:27:05 +02:00
public abstract rollback(): Promise<void>;
2020-07-24 12:13:28 +02:00
public registerModels?(): void;
2020-04-22 15:52:17 +02:00
protected async query(queryString: string): Promise<void> {
await MysqlConnectionManager.query(queryString, undefined, this.getCurrentConnection());
}
protected getCurrentConnection(): Connection {
if (!this.currentConnection) throw new Error('No current connection set.');
return this.currentConnection;
}
public setCurrentConnection(connection: Connection | null): void {
this.currentConnection = connection || undefined;
2020-06-04 17:27:05 +02:00
}
}
export interface MigrationType<M extends Migration> extends Type<M> {
new(version: number): M;
}