# 迁移是如何工作的？

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

---

<!-- EN -->
# How migrations work?

<!-- ZH -->
# 迁移是如何工作的？

<!-- EN -->
Once you get into production you'll need to synchronize model changes into the database. Typically, it is unsafe to use `synchronize: true` for schema synchronization on production once you get data in your database. Here is where migrations come to help.

<!-- ZH -->
一旦进入生产环境，你就需要把模型变更同步到数据库中。通常情况下，当数据库里已经有了数据之后，在生产环境用 `synchronize: true` 做结构同步是不安全的。迁移正是为此而来。

<!-- EN -->
A migration is just a single file with SQL queries to update a database schema and apply new changes to an existing database.

<!-- ZH -->
一个迁移就是一个包含若干 SQL 查询的文件，用来更新数据库结构并把新变更应用到已有数据库上。

<!-- EN -->
Let's say you already have a database and a `Post` entity:

<!-- ZH -->
假设你已经有一个数据库和一个 `Post` 实体：

<!-- EN -->
```typescript
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"

@Entity()
export class Post {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    title: string

    @Column()
    text: string
}
```

<!-- ZH -->
```typescript
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"

@Entity()
export class Post {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    title: string

    @Column()
    text: string
}
```

<!-- EN -->
And your entity worked in production for months without any changes. You have thousands of posts in your database.

<!-- ZH -->
而你的实体已经在生产环境中跑了几个月没有任何改动。你的数据库里有成千上万条帖子。

<!-- EN -->
Now you need to make a new release and rename `title` to `name`. What would you do?

<!-- ZH -->
现在你需要发布一个新版本，把 `title` 改名为 `name`。你会怎么做？

<!-- EN -->
You need to create a new migration with the following SQL query (PostgreSQL dialect):

<!-- ZH -->
你需要创建一个包含以下 SQL 查询的新迁移（PostgreSQL 方言）：

<!-- EN -->
```sql
ALTER TABLE "post" RENAME COLUMN "title" TO "name";
```

<!-- ZH -->
```sql
ALTER TABLE "post" RENAME COLUMN "title" TO "name";
```

<!-- EN -->
Once you run this SQL query your database schema is ready to work with your new codebase. TypeORM provides a place where you can write such sql queries and run them when needed. This place is called "migrations".

<!-- ZH -->
运行这条 SQL 查询之后，你的数据库结构就可以配合新的代码库工作了。TypeORM 提供了一个地方，让你编写这类 sql 查询并在需要时运行它们。这个地方就叫"迁移"。
