2024-05-08 16:20:31 +08:00
|
|
|
import { importModule } from '@tachybase/utils';
|
2024-06-12 11:39:09 +08:00
|
|
|
|
2023-12-17 11:16:30 +08:00
|
|
|
import _ from 'lodash';
|
2022-05-30 23:10:32 +08:00
|
|
|
import { QueryInterface, Sequelize } from 'sequelize';
|
2024-06-12 11:39:09 +08:00
|
|
|
|
2022-05-30 23:10:32 +08:00
|
|
|
import Database from './database';
|
|
|
|
|
|
|
|
export interface MigrationContext {
|
|
|
|
db: Database;
|
|
|
|
queryInterface: QueryInterface;
|
|
|
|
sequelize: Sequelize;
|
|
|
|
}
|
|
|
|
|
|
|
|
export class Migration {
|
|
|
|
public name: string;
|
|
|
|
|
2022-06-17 10:25:59 +08:00
|
|
|
public context: { db: Database; [key: string]: any };
|
2022-05-30 23:10:32 +08:00
|
|
|
|
|
|
|
constructor(context: MigrationContext) {
|
|
|
|
this.context = context;
|
|
|
|
}
|
|
|
|
|
|
|
|
get db() {
|
|
|
|
return this.context.db;
|
|
|
|
}
|
|
|
|
|
|
|
|
get sequelize() {
|
|
|
|
return this.context.db.sequelize;
|
|
|
|
}
|
|
|
|
|
|
|
|
get queryInterface() {
|
|
|
|
return this.context.db.sequelize.getQueryInterface();
|
|
|
|
}
|
|
|
|
|
|
|
|
async up() {
|
|
|
|
// todo
|
|
|
|
}
|
|
|
|
|
|
|
|
async down() {
|
|
|
|
// todo
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface MigrationItem {
|
|
|
|
name: string;
|
2023-12-21 20:39:11 +08:00
|
|
|
migration?: typeof Migration | string;
|
2022-06-17 10:25:59 +08:00
|
|
|
context?: any;
|
2022-05-30 23:10:32 +08:00
|
|
|
up?: any;
|
|
|
|
down?: any;
|
|
|
|
}
|
|
|
|
|
|
|
|
export class Migrations {
|
|
|
|
items = [];
|
|
|
|
context: any;
|
|
|
|
|
|
|
|
constructor(context: any) {
|
|
|
|
this.context = context;
|
|
|
|
}
|
|
|
|
|
|
|
|
clear() {
|
|
|
|
this.items = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
add(item: MigrationItem) {
|
|
|
|
const Migration = item.migration;
|
2023-12-21 20:39:11 +08:00
|
|
|
|
|
|
|
if (Migration && typeof Migration === 'function') {
|
2022-06-17 10:25:59 +08:00
|
|
|
const migration = new Migration({ ...this.context, ...item.context });
|
2022-05-30 23:10:32 +08:00
|
|
|
migration.name = item.name;
|
|
|
|
this.items.push(migration);
|
|
|
|
} else {
|
|
|
|
this.items.push(item);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
callback() {
|
2022-06-17 10:25:59 +08:00
|
|
|
return async (ctx) => {
|
2023-12-21 20:39:11 +08:00
|
|
|
return await Promise.all(
|
|
|
|
_.sortBy(this.items, (item) => {
|
|
|
|
const keys = item.name.split('/');
|
|
|
|
return keys.pop() || item.name;
|
|
|
|
}).map(async (item) => {
|
|
|
|
if (typeof item.migration === 'string') {
|
|
|
|
// use es module to import migration
|
|
|
|
const Migration = await importModule(item.migration);
|
|
|
|
const migration = new Migration({ ...this.context, ...item.context });
|
|
|
|
migration.name = item.name;
|
|
|
|
return migration;
|
|
|
|
}
|
|
|
|
|
|
|
|
return item;
|
|
|
|
}),
|
|
|
|
);
|
2022-05-30 23:10:32 +08:00
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|