Typeorm - 基于实体的迁移

Kev*_*RED 9 postgresql node.js typeorm

所以我将 typeorm 与 ormconfig.json 一起使用。既然synchronize不能在生产中使用,我如何运行基于实体的迁移?

我的ormconfig.json文件

{
    "type": "postgres",
    "host": "localhost",
    "port": 5432,
    "username": "",
    "password": "",
    "database": "backend-api",
    "synchronize": false,
    "logging": true,
    "migrationsRun": true,
    "entities": ["dist/entity/**/*.js"],
    "migrations": ["dist/migration/**/*.js"],
    "subscribers": ["dist/subscriber/**/*.js"],
    "cli": {
        "entitiesDir": "src/entity",
        "migrationsDir": "src/migration",
        "subscribersDir": "src/subscriber"
    }
}
Run Code Online (Sandbox Code Playgroud)

这也是我唯一的Todo.ts实体文件

import {
    BaseEntity,
    Column,
    CreateDateColumn,
    Entity,
    PrimaryGeneratedColumn,
    UpdateDateColumn,
} from 'typeorm';

@Entity()
export class Todo extends BaseEntity {
    @PrimaryGeneratedColumn()
    id: number;

    @Column('text')
    text: string;

    @Column('boolean', { default: false })
    completed: boolean;

    @CreateDateColumn()
    createdAt: Date;

    @UpdateDateColumn()
    updatedAt: Date;
}
Run Code Online (Sandbox Code Playgroud)

Kev*_*RED 5

得到了这个问题的解决方案。

所以我ormconfig.json需要稍微更新一下,

{
    "type": "postgres",
    "host": "localhost",
    "port": 5432,
    "username": "",
    "password": "",
    "database": "backend-api",
    "synchronize": false,
    "logging": true,
    "migrationsRun": false,
    "entities": ["src/entity/**/*.ts"],
    "migrations": ["src/migration/**/*.ts"],
    "subscribers": ["src/subscriber/**/*.ts"],
    "cli": {
        "entitiesDir": "src/entity",
        "migrationsDir": "src/migration",
        "subscribersDir": "src/subscriber"
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要安装ts-node来编译ts实体和迁移文件。

我创建了下面提到的脚本:

"scripts": {
    "start": "ts-node src/index.ts",
    "entity:create": "./node_modules/.bin/ts-node ./node_modules/.bin/typeorm entity:create -n",
    "migrate:generate": "./node_modules/.bin/ts-node ./node_modules/.bin/typeorm migration:generate -n",
    "migrate:run": "./node_modules/.bin/ts-node ./node_modules/.bin/typeorm migration:run",
    "migrate:revert": "./node_modules/.bin/ts-node ./node_modules/.bin/typeorm migration:revert",
    "schema:drop": "./node_modules/.bin/ts-node ./node_modules/.bin/typeorm schema:drop"
}
Run Code Online (Sandbox Code Playgroud)

并按照脚本的顺序。我学到的一件事是,您不能简单地创建一个实体文件并migration:generate在其上运行。首先需要创建一个基于typeormcli的实体。我不知道为什么,但对我来说,一旦我开始使用 cli 创建实体,一切就都到位了


Hug*_*ohm 0

要基于实体运行迁移,您可以从实体生成迁移文件,如TypeOrm 文档中有关生成的所述迁移

TypeORM能够自动生成迁移文件。

运行此命令并指定迁移的名称以生成文件:

typeorm migration:generate -n <MigrationName>
Run Code Online (Sandbox Code Playgroud)

之后,您只需要运行迁移使用 CLI

typeorm migration:run
Run Code Online (Sandbox Code Playgroud)

migrationsRun一个好的做法是在数据库配置中使用该参数来在启动时运行迁移

migrationsRun: true,
Run Code Online (Sandbox Code Playgroud)