执行与回滚
当你有迁移要在生产环境运行时,可以用 CLI 命令来运行它们:
typeorm migration:run -- -d path-to-datasource-configtypeorm migration:create 和 typeorm migration:generate 会创建 .ts 文件,除非你使用 o 标志(更多内容见生成迁移)。migration:run 和 migration:revert 命令只对 .js 文件生效。因此在运行这些命令之前,typescript 文件需要先编译。 或者,你也可以把 ts-node 与 typeorm 一起使用来运行 .ts 迁移文件。
使用 ts-node 的示例:
npx typeorm-ts-node-commonjs migration:run -- -d path-to-datasource-config在 ESM 项目中使用 ts-node 的示例:
npx typeorm-ts-node-esm migration:run -- -d path-to-datasource-confignpx typeorm-ts-node-esm migration:generate ./src/migrations/update-post-table -d ./src/data-source.ts该命令会执行所有待执行的迁移,并按它们的时间戳顺序依次运行。这意味着你所创建迁移中 up 方法里写的所有 sql 查询都会被执行。就是这样!现在你的数据库结构已经是最新的了。
Once you have a migration to run on production, you can run them using a CLI command:
typeorm migration:run -- -d path-to-datasource-configtypeorm migration:create and typeorm migration:generate will create .ts files, unless you use the o flag (see more in Generating migrations). The migration:run and migration:revert commands only work on .js files. Thus the typescript files need to be compiled before running the commands. Alternatively, you can use ts-node with typeorm to run .ts migration files.
Example with ts-node:
npx typeorm-ts-node-commonjs migration:run -- -d path-to-datasource-configExample with ts-node in ESM projects:
npx typeorm-ts-node-esm migration:run -- -d path-to-datasource-confignpx typeorm-ts-node-esm migration:generate ./src/migrations/update-post-table -d ./src/data-source.tsThis command will execute all pending migrations and run them in a sequence ordered by their timestamps. This means all sql queries written in the up methods of your created migrations will be executed. That's all! Now you have your database schema up-to-date.