数据库迁移
🌐 Database migrations
Page summary:
数据库迁移在模式同步之前运行一次性脚本,以在升级过程中保留数据。实验性 API 使用按字母顺序排列的
up()文件,并会警告缺少向下迁移和可能的表删除。
数据库迁移用于对数据库运行一次性查询,通常是在升级 Strapi 应用时修改表结构或数据。这些迁移会在应用启动时自动运行,并且在 Strapi 在启动时执行的自动模式迁移之前执行。
🌐 Database migrations exist to run one-time queries against the database, typically to modify the tables structure or the data when upgrading the Strapi application. These migrations are run automatically when the application starts and are executed before the automated schema migrations that Strapi also performs on boot.
理解数据库迁移文件
🌐 Understanding database migration files
迁移是使用存储在 ./database/migrations 中的 JavaScript 迁移文件运行的。
🌐 Migrations are run using JavaScript migration files stored in ./database/migrations.
Strapi 会自动检测迁移文件,并在下次启动时按字母顺序运行它们一次。每个新文件只执行一次。迁移会在数据库表与内容类型模式同步之前运行。
🌐 Strapi automatically detects migration files and run them once at the next startup in alphabetical order. Every new file is executed once. Migrations are run before the database tables are synced with the content-types schemas.
- 目前 Strapi 不支持向下迁移。这意味着如果你需要回滚一次迁移,必须手动操作。计划在未来实现向下迁移,但目前没有具体时间表。
- Strapi 会在没有警告的情况下删除任何未知的表。这意味着数据库迁移只能在更改 Strapi 架构时用于保留数据。
forceMigration和runMigrations数据库配置参数 可用于微调数据库迁移的行为。
迁移文件应导出函数 up(),该函数在升级时使用(例如添加一个新表 my_new_table)。
🌐 Migration files should export the function up(), which is used when upgrading (e.g. adding a new table my_new_table).
up() 函数在数据库事务中运行,这意味着如果迁移过程中查询失败,整个迁移将被取消,并且不会对数据库应用任何更改。如果在迁移函数中创建了另一个事务,它将作为嵌套事务运行。
🌐 The up() function runs in a database transaction which means if a query fails during the migration, the whole migration is cancelled, and no changes are applied to the database. If another transaction is created within the migration function, it will act as a nested transaction.
没有 CLI 可以手动执行数据库迁移。
🌐 There is no CLI to manually execute the database migrations.
创建迁移文件
🌐 Creating a migration file
创建迁移文件:
🌐 To create a migration file:
- 在
./database/migrations文件夹中,创建一个以日期和迁移名称命名的新文件(例如2022.05.10T00.00.00.name-of-my-migration.js)。确保文件名遵循此命名规则,因为文件的字母顺序决定了迁移运行的顺序。 - 将以下模板复制并粘贴到之前创建的文件中:
'use strict'
async function up(knex) {}
module.exports = { up };
- 通过在
up()函数中添加实际的迁移代码来填写模板。up()接收一个 Knex instance,该 Knex instance 已处于事务状态,可用于执行数据库查询。
迁移文件示例
module.exports = {
async up(knex) {
// You have full access to the Knex.js API with an already initialized connection to the database
// Example: renaming a table
await knex.schema.renameTable('oldName', 'newName');
// Example: renaming a column
await knex.schema.table('someTable', table => {
table.renameColumn('oldName', 'newName');
});
// Example: updating data
await knex.from('someTable').update({ columnName: 'newValue' }).where({ columnName: 'oldValue' });
},
};
使用 Strapi 实例进行迁移
🌐 Using Strapi Instance for migrations
如果用户选择不直接使用 Knex 进行迁移,而是使用 Strapi 实例,那么将迁移代码用 strapi.db.transaction() 封装是很重要的。如果不这样做,可能会导致在发生错误时迁移无法回滚。
🌐 If a user opts not to use Knex directly for migrations and instead utilizes the Strapi instance, it is important to wrap the migration code with strapi.db.transaction(). Failure to do so may result in migrations not rolling back if an error occurs.
带有 Strapi 实例的迁移文件示例
module.exports = {
async up() {
await strapi.db.transaction(async () => {
// Your migration code here
// Example: creating new entries
await strapi.entityService.create('api::article.article', {
data: {
title: 'My Article',
},
});
// Example: custom service method
await strapi.service('api::article.article').updateRelatedArticles();
});
},
};
使用 TypeScript 代码处理迁移
🌐 Handling migrations with TypeScript code
默认情况下,Strapi 在使用 TypeScript 时会在源目录而不是构建目录中查找迁移文件。这意味着除非你将 Strapi 配置为在正确的位置查找,否则 TypeScript 迁移文件将无法被找到和正确执行。
🌐 By default Strapi looks for migration files in the source directory rather than the build directory when using TypeScript. This means that TypeScript migrations won't be found and executed properly unless you configure Strapi to look in the right place.
要在 Strapi 中启用 TypeScript 迁移,你需要在数据库配置中将 useTypescriptMigrations 参数设置为 true。此设置会告诉 Strapi 在构建目录中查找迁移,而不是在源目录中查找。
🌐 To enable TypeScript migrations in Strapi, you need to set the useTypescriptMigrations parameter to true in your database configuration. This setting tells Strapi to look for migrations in the build directory instead of the source directory.
以下是如何在数据库设置中配置它:
🌐 Here's how to configure it in your database settings:
- JavaScript
- TypeScript
module.exports = ({ env }) => ({
connection: {
// Your database connection settings
},
settings: {
useTypescriptMigrations: true
}
});
export default ({ env }) => ({
connection: {
// Your database connection settings
},
settings: {
useTypescriptMigrations: true
}
});
此外,如果你想在使用 TypeScript 迁移的同时继续使用现有的 JavaScript 迁移,可以在你的 tsconfig.json 文件的编译器选项中设置 allowJs: true,如数据库配置文档中所述。
🌐 Additionally, if you want to continue using existing JavaScript migrations alongside TypeScript migrations, you can set allowJs: true in your tsconfig.json file's compiler options, as mentioned in the database configuration documentation.