add db migration
This commit is contained in:
parent
f7d85d3ba4
commit
0191343d10
@ -30,6 +30,7 @@ export async function MigrationGenerateHandler(
|
||||
}
|
||||
console.log();
|
||||
const runner = new TypeormMigrationGenerate();
|
||||
console.log('dbConfig', dbConfig);
|
||||
const dataSource = new DataSource({ ...dbConfig } as DataSourceOptions);
|
||||
console.log();
|
||||
await runner.handler({
|
||||
|
@ -22,9 +22,8 @@ export class TypeormMigrationCreate {
|
||||
const fileName = `${timestamp}-${args.name}`;
|
||||
const filePath = `${directory}/${fileName}`;
|
||||
await CommandUtils.createFile(`${filePath}.ts`, fileContent);
|
||||
console.log(
|
||||
`Migration ${chalk.blue(`${filePath}.ts`)} has been generated successfully.`,
|
||||
);
|
||||
console.log();
|
||||
console.log(`Migration ${chalk.blue(`${filePath}.ts`)} has been created successfully.`);
|
||||
} catch (e) {
|
||||
PlatformTools.logCmdErr('Error during migration creation:', e);
|
||||
process.exit(1);
|
||||
|
@ -96,7 +96,7 @@ export class TypeormMigrationGenerate {
|
||||
);
|
||||
} else {
|
||||
await CommandUtils.createFile(filePath, fileContent);
|
||||
|
||||
console.log();
|
||||
console.log(
|
||||
chalk.green(
|
||||
`Migration ${chalk.blue(filePath)} has been generated successfully.`,
|
||||
|
@ -23,6 +23,7 @@ export const createDBOptions = (options: DBConfig) => {
|
||||
{
|
||||
charset: 'utf8mb4',
|
||||
logging: ['error'],
|
||||
autoMigrate: true,
|
||||
paths: { migration: resolve(__dirname, '../../database/migrations') },
|
||||
},
|
||||
options.common ?? {},
|
||||
|
@ -21,7 +21,7 @@ type Condition = {
|
||||
|
||||
@ValidatorConstraint({ name: 'treeDataUniqueExist', async: true })
|
||||
@Injectable()
|
||||
export class TreeUniqueExistContraint implements ValidatorConstraintInterface {
|
||||
export class TreeUniqueExistConstraint implements ValidatorConstraintInterface {
|
||||
constructor(private dataSource: DataSource) {}
|
||||
|
||||
async validate(value: any, args: ValidationArguments) {
|
||||
@ -93,7 +93,7 @@ export function IsTreeUniqueExist(
|
||||
propertyName,
|
||||
options: validationOptions,
|
||||
constraints: [params],
|
||||
validator: TreeUniqueExistContraint,
|
||||
validator: TreeUniqueExistConstraint,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
@ -5,6 +5,8 @@ import { DataSource, ObjectType } from 'typeorm';
|
||||
|
||||
import { CUSTOM_REPOSITORY_METADATA } from '@/modules/database/constants';
|
||||
|
||||
import { AutoMigrateResolver } from '@/modules/database/resolver/auto.migrate';
|
||||
|
||||
import { Configure } from '../config/configure';
|
||||
|
||||
import { panic } from '../core/helpers';
|
||||
@ -12,7 +14,7 @@ import { panic } from '../core/helpers';
|
||||
import {
|
||||
DataExistConstraint,
|
||||
TreeUniqueConstraint,
|
||||
TreeUniqueExistContraint,
|
||||
TreeUniqueExistConstraint,
|
||||
UniqueConstraint,
|
||||
UniqueExistConstraint,
|
||||
} from './constraints';
|
||||
@ -34,7 +36,8 @@ export class DatabaseModule {
|
||||
UniqueConstraint,
|
||||
UniqueExistConstraint,
|
||||
TreeUniqueConstraint,
|
||||
TreeUniqueExistContraint,
|
||||
TreeUniqueExistConstraint,
|
||||
AutoMigrateResolver,
|
||||
];
|
||||
return {
|
||||
global: true,
|
||||
|
52
src/modules/database/resolver/auto.migrate.ts
Normal file
52
src/modules/database/resolver/auto.migrate.ts
Normal file
@ -0,0 +1,52 @@
|
||||
import { join } from 'path';
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ModuleRef } from '@nestjs/core';
|
||||
|
||||
import { DataSource, DataSourceOptions } from 'typeorm';
|
||||
|
||||
import { Configure } from '@/modules/config/configure';
|
||||
import { panic } from '@/modules/core/helpers';
|
||||
import { TypeormMigrationRun } from '@/modules/database/commands/typeorm.migration.run';
|
||||
import { DBOptions } from '@/modules/database/types';
|
||||
|
||||
@Injectable()
|
||||
export class AutoMigrateResolver {
|
||||
constructor(private ref: ModuleRef) {}
|
||||
|
||||
async onModuleInit() {
|
||||
const configure = this.ref.get(Configure, { strict: false });
|
||||
const { connections = [] }: DBOptions = await configure.get<DBOptions>('database');
|
||||
for (const conn of connections) {
|
||||
let dataSource: DataSource | undefined;
|
||||
if (conn.autoMigrate) {
|
||||
try {
|
||||
dataSource = new DataSource(conn as DataSourceOptions);
|
||||
const runner = new TypeormMigrationRun();
|
||||
if (dataSource && dataSource.isInitialized) {
|
||||
await dataSource.destroy();
|
||||
}
|
||||
dataSource.setOptions({
|
||||
subscribers: [],
|
||||
synchronize: false,
|
||||
migrationsRun: false,
|
||||
logging: ['error'],
|
||||
migrations: [
|
||||
join(conn.paths.migration, '**/*.ts'),
|
||||
join(conn.paths.migration, '**/*.js'),
|
||||
],
|
||||
dropSchema: false,
|
||||
});
|
||||
await dataSource.initialize();
|
||||
await runner.handler({ dataSource });
|
||||
} catch (error) {
|
||||
await panic({ message: 'Run migrations failed!', error });
|
||||
} finally {
|
||||
if (dataSource && dataSource.isInitialized) {
|
||||
await dataSource.destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -87,4 +87,9 @@ type DBAdditionalOption = {
|
||||
paths?: {
|
||||
migration?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* 是否在启动应用后自动运行迁移
|
||||
*/
|
||||
autoMigrate?: boolean;
|
||||
};
|
||||
|
Loading…
Reference in New Issue
Block a user