我想在 MySQL 中创建新表,并在应用程序在生产模式下运行时自动运行 TypeORM 迁移。
注意:此新表不是在生产模式下启动应用程序之前创建的。
根据迁移文档 https://github.com/typeorm/typeorm/blob/master/docs/migrations.md,需要使用类型迁移:运行运行迁移的命令。
由于我的新表仅在应用程序调用时创建CreateNewTableTimeStamp(inputTableName).up,此时它将触发在我的数据库中创建新表。
但我没有找到如何自动执行此迁移的解决方案,因为我不可能运行类型迁移:运行每次应用程序调用此方法来手动创建新表时。
创建该表后,我会将新数据写入该新表中。
有人可以协助解决这个问题吗?
Thanks.
我的新表代码:
class CreateNewTableTimeStamp implements MigrationInterface {
tableName: string;
constructor (inputTableName: string) {
this.tableName = inputTableName
}
async up(queryRunner: QueryRunner): Promise<any> {
await queryRunner.createTable(new Table({
name: this.tableName,
columns: [
{
name: "id",
type: "int",
isPrimary: true
},
{
name: "email",
type: "varchar",
}
]
}), true)
}
async down(queryRunner: QueryRunner): Promise<any> {
const table = await queryRunner.getTable(this.tableName);
await queryRunner.dropTable(this.tableName);
}
}
对于想要进行迁移的人们测试的目的和
不在生产环境中.
import {
createConnection,
ConnectionOptions,
Connection,
} from 'typeorm';
import { YourEntity } from 'path/to/your/entity.ts';
const testConfig: ConnectionOptions = {
type: 'mongodb',
url: 'mongodb://localhost:27017',
database: 'test',
useUnifiedTopology: true,
entities: [YourEntity],
synchronize: true,
migrations: ['migrations/*YourMigrations.ts'],
};
let connection: Connection;
connection = await createConnection({ ...testConfig });
await connection.synchronize(true);
await connection.runMigrations({
transaction: 'all',
});
运行使用:
node -r ts-node/register ./path/to/migrations.ts
or
node ./path/to/compiled/migrations.js
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)