add db migration

This commit is contained in:
liuyi 2025-06-20 14:38:22 +08:00
parent 13b5bc629a
commit 64fcacdb3d
5 changed files with 159 additions and 0 deletions

View File

@ -0,0 +1,34 @@
import { Arguments } from 'yargs';
import { CommandItem } from '@/modules/core/types';
import { MigrationCreateHandler } from '@/modules/database/commands/migration.create.handler';
import { MigrationCreateArguments } from '@/modules/database/commands/types';
/**
*
*
* @param configure
* @constructor
*/
export const CreateMigrationCommand: CommandItem<any, MigrationCreateArguments> = async ({
configure,
}) => ({
source: true,
command: [],
describe: 'Creates a new migration file',
builder: {
connection: {
type: 'string',
alias: 'c',
describe: 'Connection name of typeorm to connect database.',
},
name: {
type: 'string',
alias: 'n',
describe: 'Name of the migration class.',
demandOption: true,
},
},
handler: async (args: Arguments<MigrationCreateArguments>) =>
MigrationCreateHandler(configure, args),
});

View File

@ -0,0 +1,38 @@
import chalk from 'chalk';
import { isNil } from 'lodash';
import ora from 'ora';
import { Arguments } from 'yargs';
import { Configure } from '@/modules/config/configure';
import { panic } from '@/modules/core/helpers';
import { TypeormMigrationCreate } from '@/modules/database/commands/typeorm.migration.create';
import { MigrationCreateArguments } from '@/modules/database/commands/types';
import { DBOptions, TypeormOption } from '@/modules/database/types';
/**
*
*
* @param configure
* @param args
* @constructor
*/
export async function MigrationCreateHandler(
configure: Configure,
args: Arguments<MigrationCreateArguments>,
) {
const spinner = ora('start to create migration').start();
const cname = args.connection ?? 'default';
try {
const { connections = [] } = await configure.get<DBOptions>('database');
const dbConfig: TypeormOption = connections.find(({ name }) => name === cname);
if (isNil(dbConfig)) {
await panic(`database connection ${cname} not found`);
}
const runner = new TypeormMigrationCreate();
console.log();
await runner.handler({ name: cname, dir: dbConfig.path.migration });
spinner.start(chalk.greenBright.underline('\n 👍 Finished create migration'));
} catch (e) {
await panic({ spinner, message: 'Create migration failed!', error: e });
}
}

View File

@ -0,0 +1,45 @@
import { resolve } from 'path';
import chalk from 'chalk';
import { CommandUtils } from 'typeorm/commands/CommandUtils';
import { PlatformTools } from 'typeorm/platform/PlatformTools';
import { camelCase } from 'typeorm/util/StringUtils';
import { MigrationCreateOptions } from '@/modules/database/commands/types';
type HandleOptions = MigrationCreateOptions & { dir: string };
export class TypeormMigrationCreate {
async handler(args: HandleOptions) {
try {
const timestamp = new Date().getTime();
const directory = args.dir.startsWith('/')
? args.dir
: resolve(process.cwd(), args.dir);
const fileContent = TypeormMigrationCreate.getTemplate(args.name, timestamp);
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.`,
);
} catch (e) {
PlatformTools.logCmdErr('Error during migration creation:', e);
process.exit(1);
}
}
protected static getTemplate(name: string, timestamp: number): string {
return `import typeorm = require('typeorm');
class ${camelCase(name, true)}${timestamp} implements typeorm.MigrationInterface {
public async up(queryRunner: typeorm.QueryRunner): Promise<void> {
}
public async down(queryRunner: typeorm.QueryRunner): Promise<void> {
}
}
`;
}
}

View File

@ -0,0 +1,8 @@
import { DataSource } from 'typeorm';
import { MigrationGenerateOptions } from '@/modules/database/commands/types';
type HandlerOptions = MigrationGenerateOptions & { dataSource: DataSource };
export class TypeormMigrationGenerate {
async handler(args: HandlerOptions) {}
}

View File

@ -0,0 +1,34 @@
import { Arguments } from 'yargs';
/**
*
*/
export type TypeOrmArguments = Arguments<{ connection?: string }>;
/**
*
*/
export type MigrationCreateArguments = TypeOrmArguments & MigrationCreateOptions;
/**
*
*/
export interface MigrationCreateOptions {
name?: string;
}
/**
*
*/
export type MigrationGenerateArguments = TypeOrmArguments & MigrationCreateOptions;
/**
*
*/
export interface MigrationGenerateOptions {
name?: string;
run?: boolean;
pretty?: boolean;
dryrun?: boolean;
check?: boolean;
}