使用迁移策略打开资产数据库

时间:2019-08-23 07:21:13

标签: database flutter migration sqflite

我遵循本指南Opening an asset database来打开资产数据库并将其复制到我的文件系统中,但使用“ readOnly:true”,因为我希望用户在应用程序内修改数据库。

  initDB() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "TEST.db");

    var exists = await databaseExists(path);

    if (!exists) {
      // Should happen only the first time you launch your application
      print("Creating new copy from asset");

      // Make sure the parent directory exists
      try {
        await Directory(dirname(path)).create(recursive: true);
      } catch (_) {}

      // Copy from asset
      ByteData data = await rootBundle.load(join("assets", "test.db"));
      List<int> bytes =
          data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);

      // Write and flush the bytes written
      await File(path).writeAsBytes(bytes, flush: true);
    } else {
      print("Opening existing database");
    }
    // open the database
    return await openDatabase(path, version: 1, onUpgrade: _onUpgrade);
  }

这很好用。

但是稍后我想修改资产数据库,例如添加新的行,列或表,甚至更改已存在的特定列中的值。当我这样做时,我想用修改后的资产数据库更新文件系统中的复制数据库。为此,我使用onUpgrade。

  _onUpgrade(Database db, int oldVersion, int newVersion) async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "TEST.db");

    // Delete old database and load new asset database
    await deleteDatabase(path);
    try {
      await Directory(dirname(path)).create(recursive: true);
    } catch (_) {}

    ByteData data = await rootBundle.load(join("assets", "test.db"));
    List<int> bytes =
        data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    await new File(path).writeAsBytes(bytes, flush: true);

    // Add new table

    // Add new row or column

    // Update column
  }

我只知道如何在更改版本后删除文件系统中的数据库,但是我不想删除用户所做的数据库更改。 如何将新资产数据库与文件系统中的数据库合并?如何添加新的表格,列或行?以及如何替换列?

1 个答案:

答案 0 :(得分:1)

您将不得不使用readOnly = false打开它。

然后,当您调用onUpgrade时,必须运行SQL查询以使用ALTER TABLE命令更改表。

final Future<Database> database = openDatabase(
  // Set the path to the database.
  join(await getDatabasesPath(), 'mydatabase.db'),

  onUpgrade: (db, version ...) {
    return db.execute(
      "ALTER TABLE ... ADD COLUMN ...",
    );
  },
  // Set the version to upgrade
  version: 2,
);
相关问题