首页
/ Drift数据库迁移中的ALTER TABLE策略解析

Drift数据库迁移中的ALTER TABLE策略解析

2025-06-28 03:31:10作者:冯爽妲Honey

引言

在使用Drift(原Moor)进行Flutter应用数据库开发时,表结构变更是常见的需求。本文将通过一个实际案例,深入分析如何在Drift中正确执行ALTER TABLE操作,特别是当需要同时修改列属性和添加新列时的最佳实践。

案例背景

开发者需要对现有的ExampleTable进行两项修改:

  1. dueDate列改为可空(nullable)
  2. 添加一个新的布尔列withoutDueDate

初始表结构如下:

@DataClassName('ExampleCollection')
class ExampleTable extends Table {
  IntColumn get id => integer().autoIncrement()();
  RealColumn get amount => real()();
  DateTimeColumn get dueDate => dateTime()();
  TextColumn get status => textEnum<PeopleStatus>()();
  DateTimeColumn get creationDate => dateTime().withDefault(currentDate)();
}

修改后的表结构需要变为:

@DataClassName('ExampleCollection')
class ExampleTable extends Table {
  IntColumn get id => integer().autoIncrement()();
  RealColumn get amount => real()();
  DateTimeColumn get dueDate => dateTime().nullable()();
  BoolColumn get withoutDueDate => boolean().withDefault(const Constant(true))();
  TextColumn get status => textEnum<PeopleStatus>()();
  DateTimeColumn get creationDate => dateTime().withDefault(currentDate)();
}

常见错误做法

开发者最初尝试的迁移策略是:

onUpgrade: (Migrator m, int from, int to) async {
  await transaction(() async {
    if (from < 2) {
      // 修改dueDate为nullable
      await m.alterTable(
        TableMigration(exampleTable, columnTransformer: {
          exampleTable.dueDate: exampleTable.dueDate.cast<DateTime>(),
        }),
      );
      
      // 添加新列withoutDueDate
      await m.addColumn(exampleTable, exampleTable.withoutDueDate);
    }
  });
}

这种实现会导致迁移失败,原因在于对Drift的ALTER TABLE机制理解不足。

问题分析

Drift的alterTable方法实际上是通过以下步骤工作的:

  1. 创建一个临时表(包含新结构)
  2. 将旧表数据复制到临时表
  3. 删除旧表
  4. 将临时表重命名为原表名

关键在于第二步的数据复制过程:系统会尝试从旧表中读取所有列的值并插入到新表中。当新表包含旧表不存在的列时,如果不明确指定,复制操作会失败。

正确解决方案

正确的做法是在TableMigration中通过newColumns参数明确指定新增列:

await m.alterTable(
  TableMigration(
    exampleTable,
    columnTransformer: {
      exampleTable.dueDate: exampleTable.dueDate.cast<DateTime>(),
    },
    newColumns: [exampleTable.withoutDueDate],
  ),
);

这样修改后:

  1. alterTable会创建包含所有列(包括新列)的新表结构
  2. 对于newColumns中指定的列,系统会使用其默认值而不是尝试从旧表复制
  3. 由于新表已经包含所有列,不再需要单独的addColumn调用

迁移最佳实践

  1. 使用Schema导出:建议使用Drift的schema导出功能,将每个版本的数据库结构保存为JSON文件。这有助于编写迁移测试和确保迁移代码的长期稳定性。

  2. 原子性操作:尽量在一个alterTable调用中完成所有相关修改,而不是拆分成多个操作。

  3. 版本兼容性:当后续版本再次修改表结构时,确保早期版本的迁移代码不受影响。使用schema导出可以很好地解决这个问题。

  4. 测试验证:为重要迁移编写单元测试,验证从旧版本到新版本的迁移是否按预期工作。

总结

在Drift中进行表结构变更时,理解alterTable的内部机制至关重要。对于同时包含列修改和新增列的场景,应使用newColumns参数明确指定新增列,而不是单独调用addColumn。遵循这些最佳实践可以确保数据库迁移过程顺利可靠,为应用的长期维护奠定良好基础。

登录后查看全文
热门项目推荐
相关项目推荐