迁移是如何工作的?
一旦进入生产环境,你就需要把模型变更同步到数据库中。通常情况下,当数据库里已经有了数据之后,在生产环境用 synchronize: true 做结构同步是不安全的。迁移正是为此而来。
一个迁移就是一个包含若干 SQL 查询的文件,用来更新数据库结构并把新变更应用到已有数据库上。
假设你已经有一个数据库和一个 Post 实体:
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
text: string
}而你的实体已经在生产环境中跑了几个月没有任何改动。你的数据库里有成千上万条帖子。
现在你需要发布一个新版本,把 title 改名为 name。你会怎么做?
你需要创建一个包含以下 SQL 查询的新迁移(PostgreSQL 方言):
ALTER TABLE "post" RENAME COLUMN "title" TO "name";运行这条 SQL 查询之后,你的数据库结构就可以配合新的代码库工作了。TypeORM 提供了一个地方,让你编写这类 sql 查询并在需要时运行它们。这个地方就叫"迁移"。
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.
A migration is just a single file with SQL queries to update a database schema and apply new changes to an existing database.
Let's say you already have a database and a Post entity:
import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number
@Column()
title: string
@Column()
text: string
}And your entity worked in production for months without any changes. You have thousands of posts in your database.
Now you need to make a new release and rename title to name. What would you do?
You need to create a new migration with the following SQL query (PostgreSQL dialect):
ALTER TABLE "post" RENAME COLUMN "title" TO "name";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".