配置
在使用迁移之前,你需要正确配置 DataSource 选项:
export default new DataSource({
// 基础配置
synchronize: false,
migrations: [__dirname + "/migrations/**/*{.js,.ts}"],
// 可选
migrationsRun: false,
migrationsTableName: "migrations",
migrationsTransactionMode: "all",
// 其他选项...
})synchronise
关闭自动结构同步对使用迁移来说是必需的。否则迁移就毫无意义了。
migrations
定义需要被 TypeORM 加载的迁移列表。它既接受迁移类,也接受用于加载的目录。
最简单的做法是指定存放迁移文件的目录(支持 glob 模式):
migrations: [__dirname + "/migrations/**/*{.js,.ts}"]同时定义 .js 和 .ts 两种扩展名,可以让你在开发环境中运行迁移,也能在生产环境中从编译后的 JavaScript 运行它们(例如在 Docker 镜像中)。
或者你也可以指定确切的类,以获得更细粒度的控制:
import FirstMigration from "./migrations/TIMESTAMP-first-migration"
import SecondMigration from "./migrations/TIMESTAMP-second-migration"
export default new DataSource({
migrations: [FirstMigration, SecondMigration],
})但这也意味着更多的手工维护,并且容易出错。
migrationsRun- 表示是否在每次应用启动时自动运行迁移。
可选配置
migrationsRun
表示是否在每次应用启动时自动运行迁移。默认值:false
migrationsTableName
你可能想指定用于存放已执行迁移信息的表名。默认它叫 'migrations'。
migrationsTableName: "some_custom_migrations_table"migrationsTransactionMode
控制运行迁移时的事务模式。可选值为:
all(默认)- 把整批迁移包在单个事务中运行noneeach
Before working with migrations you need to setup your DataSource options properly:
export default new DataSource({
// basic setup
synchronize: false,
migrations: [__dirname + "/migrations/**/*{.js,.ts}"],
// optional
migrationsRun: false,
migrationsTableName: "migrations",
migrationsTransactionMode: "all",
// other options...
})synchronise
Turning off automatic schema synchronisation is essential for working with migrations. Otherwise they would make no sense.
migrations
Defines list of migrations that need to be loaded by TypeORM. It accepts both migration classes and directories from which to load.
The easiest is to specify the directory where your migration files are located (glob patterns are supported):
migrations: [__dirname + "/migrations/**/*{.js,.ts}"]Defining both .js and .ts extensions would allow you to run migrations in development and from compiled to JavaScript for production (eg. from Docker image).
Alternatively you could also specify exact classes to get more fine grained control:
import FirstMigration from "./migrations/TIMESTAMP-first-migration"
import SecondMigration from "./migrations/TIMESTAMP-second-migration"
export default new DataSource({
migrations: [FirstMigration, SecondMigration],
})but it also requires more manual work and can be error prone.
migrationsRun- Indicates if migrations should be auto-run on every application launch.
Optional settings
migrationsRun
Indicates if migrations should be auto-run on every application launch. Default: false
migrationsTableName
You might want to specify the name of the table that will store information about executed migrations. By default it is called 'migrations'.
migrationsTableName: "some_custom_migrations_table"migrationsTransactionMode
Controls transaction mode when running migrations. Possible options are:
all(default) - wraps migrations run into a single transactionnoneeach