add db migration
This commit is contained in:
parent
f7d85d3ba4
commit
0191343d10
@ -30,6 +30,7 @@ export async function MigrationGenerateHandler(
|
|||||||
}
|
}
|
||||||
console.log();
|
console.log();
|
||||||
const runner = new TypeormMigrationGenerate();
|
const runner = new TypeormMigrationGenerate();
|
||||||
|
console.log('dbConfig', dbConfig);
|
||||||
const dataSource = new DataSource({ ...dbConfig } as DataSourceOptions);
|
const dataSource = new DataSource({ ...dbConfig } as DataSourceOptions);
|
||||||
console.log();
|
console.log();
|
||||||
await runner.handler({
|
await runner.handler({
|
||||||
|
@ -22,9 +22,8 @@ export class TypeormMigrationCreate {
|
|||||||
const fileName = `${timestamp}-${args.name}`;
|
const fileName = `${timestamp}-${args.name}`;
|
||||||
const filePath = `${directory}/${fileName}`;
|
const filePath = `${directory}/${fileName}`;
|
||||||
await CommandUtils.createFile(`${filePath}.ts`, fileContent);
|
await CommandUtils.createFile(`${filePath}.ts`, fileContent);
|
||||||
console.log(
|
console.log();
|
||||||
`Migration ${chalk.blue(`${filePath}.ts`)} has been generated successfully.`,
|
console.log(`Migration ${chalk.blue(`${filePath}.ts`)} has been created successfully.`);
|
||||||
);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
PlatformTools.logCmdErr('Error during migration creation:', e);
|
PlatformTools.logCmdErr('Error during migration creation:', e);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
|
@ -96,7 +96,7 @@ export class TypeormMigrationGenerate {
|
|||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
await CommandUtils.createFile(filePath, fileContent);
|
await CommandUtils.createFile(filePath, fileContent);
|
||||||
|
console.log();
|
||||||
console.log(
|
console.log(
|
||||||
chalk.green(
|
chalk.green(
|
||||||
`Migration ${chalk.blue(filePath)} has been generated successfully.`,
|
`Migration ${chalk.blue(filePath)} has been generated successfully.`,
|
||||||
|
@ -23,6 +23,7 @@ export const createDBOptions = (options: DBConfig) => {
|
|||||||
{
|
{
|
||||||
charset: 'utf8mb4',
|
charset: 'utf8mb4',
|
||||||
logging: ['error'],
|
logging: ['error'],
|
||||||
|
autoMigrate: true,
|
||||||
paths: { migration: resolve(__dirname, '../../database/migrations') },
|
paths: { migration: resolve(__dirname, '../../database/migrations') },
|
||||||
},
|
},
|
||||||
options.common ?? {},
|
options.common ?? {},
|
||||||
|
@ -21,7 +21,7 @@ type Condition = {
|
|||||||
|
|
||||||
@ValidatorConstraint({ name: 'treeDataUniqueExist', async: true })
|
@ValidatorConstraint({ name: 'treeDataUniqueExist', async: true })
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class TreeUniqueExistContraint implements ValidatorConstraintInterface {
|
export class TreeUniqueExistConstraint implements ValidatorConstraintInterface {
|
||||||
constructor(private dataSource: DataSource) {}
|
constructor(private dataSource: DataSource) {}
|
||||||
|
|
||||||
async validate(value: any, args: ValidationArguments) {
|
async validate(value: any, args: ValidationArguments) {
|
||||||
@ -93,7 +93,7 @@ export function IsTreeUniqueExist(
|
|||||||
propertyName,
|
propertyName,
|
||||||
options: validationOptions,
|
options: validationOptions,
|
||||||
constraints: [params],
|
constraints: [params],
|
||||||
validator: TreeUniqueExistContraint,
|
validator: TreeUniqueExistConstraint,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
@ -5,6 +5,8 @@ import { DataSource, ObjectType } from 'typeorm';
|
|||||||
|
|
||||||
import { CUSTOM_REPOSITORY_METADATA } from '@/modules/database/constants';
|
import { CUSTOM_REPOSITORY_METADATA } from '@/modules/database/constants';
|
||||||
|
|
||||||
|
import { AutoMigrateResolver } from '@/modules/database/resolver/auto.migrate';
|
||||||
|
|
||||||
import { Configure } from '../config/configure';
|
import { Configure } from '../config/configure';
|
||||||
|
|
||||||
import { panic } from '../core/helpers';
|
import { panic } from '../core/helpers';
|
||||||
@ -12,7 +14,7 @@ import { panic } from '../core/helpers';
|
|||||||
import {
|
import {
|
||||||
DataExistConstraint,
|
DataExistConstraint,
|
||||||
TreeUniqueConstraint,
|
TreeUniqueConstraint,
|
||||||
TreeUniqueExistContraint,
|
TreeUniqueExistConstraint,
|
||||||
UniqueConstraint,
|
UniqueConstraint,
|
||||||
UniqueExistConstraint,
|
UniqueExistConstraint,
|
||||||
} from './constraints';
|
} from './constraints';
|
||||||
@ -34,7 +36,8 @@ export class DatabaseModule {
|
|||||||
UniqueConstraint,
|
UniqueConstraint,
|
||||||
UniqueExistConstraint,
|
UniqueExistConstraint,
|
||||||
TreeUniqueConstraint,
|
TreeUniqueConstraint,
|
||||||
TreeUniqueExistContraint,
|
TreeUniqueExistConstraint,
|
||||||
|
AutoMigrateResolver,
|
||||||
];
|
];
|
||||||
return {
|
return {
|
||||||
global: true,
|
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?: {
|
paths?: {
|
||||||
migration?: string;
|
migration?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否在启动应用后自动运行迁移
|
||||||
|
*/
|
||||||
|
autoMigrate?: boolean;
|
||||||
};
|
};
|
||||||
|
Loading…
Reference in New Issue
Block a user