我正在编写一个React,它严重依赖本地存储,并且选择了TypeORM来处理这个问题。
我现在进入了一个我的项目是活的阶段,我想添加新的功能,需要调整我的数据模型。首先,我使用了react本机示例项目。我已经在此基础上构建了我的数据模型,现在我想要实现对它的迁移。
似乎没有明确的手册/指南关于如何执行迁移的反应-土著人。由于我无法访问用户的数据库,所以无法手动运行迁移。到目前为止,我发现连接设置中有一个“migrationsRun”选项,可以设置为true,如果需要的话,强制迁移在应用程序的每次启动时执行。
那么问题是:应该如何创建实际的迁移,它们应该是什么样子(普通sql查询?),我应该把它们放在哪里呢?
任何关于反应本地应用程序迁移的指导都是非常有帮助的。
发布于 2020-01-23 21:48:29
我也遇到了同样的问题,并通过提供以下属性(作为createConnection选项),设法使迁移在一个react本机上下文中运行:
falsetruemigrationFilemigrationFile是直接导入的(而不是使用文件路径regex),如下所示(带有内联SQL语句):
import { MigrationInterface } from 'typeorm'
module.exports = class PostRefactoring1579804977343 implements MigrationInterface {
async up(queryRunner) {
await queryRunner.query(`ALTER TABLE "workouts" ADD COLUMN "questionSetId" text`)
}
async down(queryRunner) {
await queryRunner.query(`ALTER TABLE "workouts" DROP COLUMN "questionSetId"`)
}
}上面的迁移文件与您将在https://typeorm.io/#/migrations上看到的示例略有不同,因为我没有使用TypeScript,而且在直接导入文件时必须添加module.exports
我在这里发现的神奇的migrationsRun属性(几乎)是我在这里发现的(几乎)无文档的发现,因为它似乎是在react本机中工作的。
您可以根据需要向migrations数组配置添加更多迁移文件,并确保为它们提供一个具有适当时间戳的惟一类名。它似乎保存了迁移已运行的设备日志,以阻止它们在同一设备上多次运行。
注意:拥有synchronize: false的要求意味着您需要在首次安装应用程序时对模式进行初始同步(我最初使用AsyncStorage中的一个标志来指示第一个应用程序安装)
替代方法
上述方法意味着,在初始用户安装之后,我们将手动维护模式设置。然而,我非常喜欢让模式在可能的情况下自动管理的想法--使用迁移来操作数据。
因此,实现这一目标的另一种方法是在初始化连接时直接调用synchronize和runMigrations方法。在本例中,您需要检查迁移脚本中是否存在特定的表,因为它们将首先运行,因此,如果用户在安装后第一次打开应用程序,则它们需要更新的表可能还不存在。
连接选项:
export const initialiseDataStoreService = async () => {
const connection = await createConnection({
type: 'react-native',
database: 'main.sqlite',
location: 'default',
logging: [ 'error', 'schema'],
entities: [
CoreData,
Workouts,
],
migrations: [PostRefactoring1579804977343],
})
await connection.runMigrations()
await connection.synchronize()
return connection
}更新后的迁移脚本:
import { MigrationInterface, TableColumn } from 'typeorm'
module.exports = class PostRefactoring1579804977343 implements MigrationInterface {
async up(queryRunner) {
const hasWorkoutsTable = await queryRunner.hasTable('workouts')
if (hasWorkoutsTable) {
await queryRunner.addColumn(
'workouts',
new TableColumn({
name: 'questionSetId',
type: 'text',
// we make the new field nullable in order to enable the update
// for existing data (schema sync will later update this column to be non
// nullable)
isNullable: true,
}),
)
await queryRunner.query(
`UPDATE workouts SET questionSetId = "MIGRATION-PLACEHOLDER" WHERE questionSetId IS NULL`,
)
}
}
async down(queryRunner) {
const hasWorkoutsTable = await queryRunner.hasTable('workouts')
if (hasWorkoutsTable) {
await queryRunner.dropColumn('workouts', 'questionSetId')
}
}
}https://stackoverflow.com/questions/59101285
复制相似问题