# 自动生成

> 英文标题：Generating
> 官网原文：https://typeorm.io/docs/migrations/generating
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 19 块

---

<!-- EN -->
# Generating

<!-- ZH -->
# 自动生成

<!-- EN -->
TypeORM is able to automatically generate migration files based on the changes you made to the entities, comparing them with existing database schema on the server.

<!-- ZH -->
TypeORM 能够根据你对实体所做的变更，把它与服务器上已有的数据库结构做比较，从而自动生成迁移文件。

<!-- EN -->
Automatic migration generation creates a new migration file and writes all sql queries that must be executed to update the database. If no changes are detected, the command will exit with code `1`.

<!-- ZH -->
自动迁移生成会创建一个新的迁移文件，并写入所有必须执行的 sql 查询以更新数据库。如果没有检测到任何变更，该命令会以退出码 `1` 退出。

<!-- EN -->
Let's say you have a `Post` entity with a `title` column, and you have changed the name `title` to `name`.

<!-- ZH -->
假设你有一个带 `title` 列的 `Post` 实体，并且你把 `title` 改名成了 `name`。

<!-- EN -->
You can generate migration with of the following command:

<!-- ZH -->
你可以用以下命令生成迁移：

<!-- EN -->
```shell
typeorm migration:generate -d <path/to/datasource> <migration-name>
```

<!-- ZH -->
```shell
typeorm migration:generate -d <path/to/datasource> <migration-name>
```

<!-- EN -->
The `-d` argument value should specify the path where your [DataSource](https://typeorm.io/docs/data-source/data-source) instance is defined.

<!-- ZH -->
`-d` 参数的值应当指定定义 [DataSource](https://typeorm.io/docs/data-source/data-source) 实例的路径。

<!-- EN -->
Alternatively you can also specify name with `--name` param

<!-- ZH -->
或者你也可以用 `--name` 参数指定名称

<!-- EN -->
```shell
typeorm migration:generate -- -d <path/to/datasource> --name=<migration-name>
```

<!-- ZH -->
```shell
typeorm migration:generate -- -d <path/to/datasource> --name=<migration-name>
```

<!-- EN -->
or use a full path:

<!-- ZH -->
或者使用完整路径：

<!-- EN -->
```shell
typeorm migration:generate -d <path/to/datasource> <path/to/migrations>/<migration-name>
```

<!-- ZH -->
```shell
typeorm migration:generate -d <path/to/datasource> <path/to/migrations>/<migration-name>
```

<!-- EN -->
Assuming you used `post-refactoring` as a name, it will generate a new file called `{TIMESTAMP}-post-refactoring.ts` with the following content:

<!-- ZH -->
假设你用 `post-refactoring` 作为名称，它会生成一个名为 `{TIMESTAMP}-post-refactoring.ts` 的新文件，内容如下：

<!-- EN -->
```typescript
import { MigrationInterface, QueryRunner } from "typeorm"

export class PostRefactoringTIMESTAMP implements MigrationInterface {
    async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(
            `ALTER TABLE "post" ALTER COLUMN "title" RENAME TO "name"`,
        )
    }

    async down(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(
            `ALTER TABLE "post" ALTER COLUMN "name" RENAME TO "title"`,
        )
    }
}
```

<!-- ZH -->
```typescript
import { MigrationInterface, QueryRunner } from "typeorm"

export class PostRefactoringTIMESTAMP implements MigrationInterface {
    async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(
            `ALTER TABLE "post" ALTER COLUMN "title" RENAME TO "name"`,
        )
    }

    async down(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(
            `ALTER TABLE "post" ALTER COLUMN "name" RENAME TO "title"`,
        )
    }
}
```

<!-- EN -->
Alternatively, you can also output your migrations as Javascript files using the `o` (alias for `--outputJs`) flag. This is useful for Javascript only projects in which TypeScript additional packages are not installed. This command, will generate a new migration file `{TIMESTAMP}-PostRefactoring.js` with the following content:

<!-- ZH -->
另外，你也可以用 `o`（`--outputJs` 的别名）标志把迁移输出为 Javascript 文件。这对那些没有安装 TypeScript 相关包的纯 Javascript 项目很有用。该命令会生成一个新的迁移文件 `{TIMESTAMP}-PostRefactoring.js`，内容如下：

<!-- EN -->
```javascript
/**
 * @typedef {import('typeorm').MigrationInterface} MigrationInterface
 * @typedef {import('typeorm').QueryRunner} QueryRunner
 */

/**
 * @class
 * @implements {MigrationInterface}
 */
module.exports = class PostRefactoringTIMESTAMP {
    /**
     * @param {QueryRunner} queryRunner
     */
    async up(queryRunner) {
        await queryRunner.query(
            `ALTER TABLE "post" ALTER COLUMN "title" RENAME TO "name"`,
        )
    }

    /**
     * @param {QueryRunner} queryRunner
     */
    async down(queryRunner) {
        await queryRunner.query(
            `ALTER TABLE "post" ALTER COLUMN "name" RENAME TO "title"`,
        )
    }
}
```

<!-- ZH -->
```javascript
/**
 * @typedef {import('typeorm').MigrationInterface} MigrationInterface
 * @typedef {import('typeorm').QueryRunner} QueryRunner
 */

/**
 * @class
 * @implements {MigrationInterface}
 */
module.exports = class PostRefactoringTIMESTAMP {
    /**
     * @param {QueryRunner} queryRunner
     */
    async up(queryRunner) {
        await queryRunner.query(
            `ALTER TABLE "post" ALTER COLUMN "title" RENAME TO "name"`,
        )
    }

    /**
     * @param {QueryRunner} queryRunner
     */
    async down(queryRunner) {
        await queryRunner.query(
            `ALTER TABLE "post" ALTER COLUMN "name" RENAME TO "title"`,
        )
    }
}
```

<!-- EN -->
By default, it generates CommonJS JavaScript code with the `o` (alias for `--outputJs`) flag, but you can also generate ESM code with the `esm` flag. This is useful for Javascript projects that use ESM:

<!-- ZH -->
默认情况下，`o`（`--outputJs` 的别名）标志会生成 CommonJS JavaScript 代码，但你也可以用 `esm` 标志生成 ESM 代码。这对使用 ESM 的 Javascript 项目很有用：

<!-- EN -->
```javascript
/**
 * @typedef {import('typeorm').MigrationInterface} MigrationInterface
 * @typedef {import('typeorm').QueryRunner} QueryRunner
 */

/**
 * @class
 * @implements {MigrationInterface}
 */
export class PostRefactoringTIMESTAMP {
    /**
     * @param {QueryRunner} queryRunner
     */
    async up(queryRunner) {
        await queryRunner.query(
            `ALTER TABLE "post" ALTER COLUMN "title" RENAME TO "name"`,
        )
    }

    /**
     * @param {QueryRunner} queryRunner
     */
    async down(queryRunner) {
        await queryRunner.query(
            `ALTER TABLE "post" ALTER COLUMN "name" RENAME TO "title"`,
        )
    }
}
```

<!-- ZH -->
```javascript
/**
 * @typedef {import('typeorm').MigrationInterface} MigrationInterface
 * @typedef {import('typeorm').QueryRunner} QueryRunner
 */

/**
 * @class
 * @implements {MigrationInterface}
 */
export class PostRefactoringTIMESTAMP {
    /**
     * @param {QueryRunner} queryRunner
     */
    async up(queryRunner) {
        await queryRunner.query(
            `ALTER TABLE "post" ALTER COLUMN "title" RENAME TO "name"`,
        )
    }

    /**
     * @param {QueryRunner} queryRunner
     */
    async down(queryRunner) {
        await queryRunner.query(
            `ALTER TABLE "post" ALTER COLUMN "name" RENAME TO "title"`,
        )
    }
}
```

<!-- EN -->
See, you don't need to write the queries on your own.

<!-- ZH -->
看，你不需要自己写这些查询。

<!-- EN -->
The rule of thumb for generating migrations is that you generate them after **each** change you made to your models. To apply multi-line formatting to your generated migration queries, use the `p` (alias for `--pretty`) flag.

<!-- ZH -->
生成迁移的经验法则是：你对模型做出 **每一次** 改动之后都生成一次迁移。要给生成的迁移查询应用多行格式化，请使用 `p`（`--pretty` 的别名）标志。
