[英]TypeORM - How to create new table and run migration automatically in production mode?
我想在 MySQL 中创建新表并在应用程序在生产模式下运行时自动运行 TypeORM 迁移。
注意:这个新表不是在生产模式下启动应用程序之前创建的。
根据Migration Documentation ,它需要使用typeorm migration:run命令来运行迁移。
由于我的新表仅在应用程序调用CreateNewTableTimeStamp(inputTableName).up时创建,此时它将触发在我的数据库中创建新表。
但是我没有找到如何自动执行此迁移的解决方案,因为我不可能在每次应用程序调用此方法创建新表时手动运行typeorm migration:run 。
这张表创建好后,我会在之后将新数据写入这个新表中。
有人可以帮助解决这个问题吗?
谢谢。
我的新表代码:
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);
}
}
正如@zenbeni 在评论中提到的,不建议从您的服务器代码运行迁移,因为迁移应该始终是不可变的和可重播的。
因此,我会改变我的设计,不要从我的服务器代码进行迁移。
对于希望出于测试目的运行迁移的人:不在生产环境中。
`
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',
});
// 运行使用:
节点-r ts-node/register ./path/to/migrations.ts
// 或者
节点 ./path/to/compiled/migrations.js
`
跑
yarn typeorm migration:create -n users
(表名称)
表代码示例:
import { MigrationInterface, QueryRunner, Table } from 'typeorm';
export class createUsers1585025619325 implements MigrationInterface {
private table = new Table({
name: 'users',
columns: [
{
name: 'id',
type: 'integer',
isPrimary: true,
isGenerated: true, // Auto-increment
generationStrategy: 'increment',
},
{
name: 'email',
type: 'varchar',
length: '255',
isUnique: true,
isNullable: false,
},
{
name: 'created_at',
type: 'timestamptz',
isNullable: false,
default: 'now()',
},
{
name: 'updated_at',
type: 'timestamptz',
isNullable: false,
default: 'now()',
},
],
});
public async up(queryRunner: QueryRunner): Promise<any> {
await queryRunner.createTable(this.table);
}
public async down(queryRunner: QueryRunner): Promise<any> {
await queryRunner.dropTable(this.table);
}
}
使用以下命令运行创建的迁移:
yarn typeorm migration:run
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.