flutter 即使在使用事务对象和批处理之后,SQflite也会在批量插入时被锁定

42fyovps  于 2023-05-08  发布在  Flutter
关注(0)|答案(1)|浏览(276)

我是新的Flutter,我做批量插入sqflite数据库。我已经尝试使用事务和批处理对象,但我的问题仍然存在,数据库被锁定。
这就是我正在做的。

Future<List<ShopsModel>> fetchShops() async{
    int count = 0;
    List<ShopsModel> shopsList = [];
    int id = 0;
    String date = "";
    List<SyncDataModel> syncList = await DatabaseHelper.instance.getSyncDataHistory();
    syncList.forEach((element) {
      id = element.SyncID!;
      date = element.ShopSyncDate == null ? "" : element.ShopSyncDate!;
    });
    //Info.startProgress();
    String response = await ApiServices.getMethodApi("${ApiUrls.IMPORT_SHOPS}?date=$date");

    if(response.isEmpty || response == null){
      return shopsList;
    }

    var shopsApiResponse = shopsApiResponseFromJson(response);

    if(shopsApiResponse.data != null){
      shopsApiResponse.data!.forEach((element) async{
        await insertShops(element);
        count++;
        if(count == 1){
          syncList.length == 0 ? await DatabaseHelper.instance.insertSyncDataHistory(
              SyncDataModel(
                  ShopSyncDate: DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now()),
                  LastSyncDate: DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now())
              )) :
          await DatabaseHelper.instance.updateShopSyncDate(
              DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now()), id);
        }
      });
    }
    return shopsList;
  }

  Future insertShops(ShopsModel row) async{
    var shopsRow = await DatabaseHelper.instance.getShopByShopId(row.shopID!);
    if(shopsRow.IsModify == 0 || shopsRow.IsModify == null) {
      var result = await DatabaseHelper.instance.deleteImportedShops(
          row.shopID!, DateFormat('yyyy-MM-dd HH:mm:ss').format(
          DateTime.parse(row.updatedOn!)));
      if (result > 0) {
        print('Shop has been deleted');
      }
      await DatabaseHelper.instance.insertShops(
          ShopsModel(
              shopID: row.shopID,
              shopName: row.shopName,
              shopCode: row.shopCode,
              contactPerson: row.contactPerson,
              contactNo: row.contactNo,
              nTNNO: row.nTNNO,
              regionID: row.regionID,
              areaID: row.areaID,
              salePersonID: row.salePersonID,
              createdByID: row.createdByID,
              updatedByID: row.updatedByID,
              systemNotes: row.systemNotes,
              remarks: row.remarks,
              description: row.description,
              entryDate: DateFormat('yyyy-MM-dd HH:mm:ss').format(
                  DateTime.parse(row.entryDate!)),
              branchID: row.branchID,
              longitiude: row.longitiude,
              latitiude: row.latitiude,
              googleAddress: row.googleAddress,
              createdOn: DateFormat('yyyy-MM-dd HH:mm:ss').format(
                  DateTime.parse(row.createdOn!)),
              updatedOn: DateFormat('yyyy-MM-dd HH:mm:ss').format(
                  DateTime.parse(row.updatedOn!)),
              tradeChannelID: row.tradeChannelID,
              route: row.route,
              vPO: row.vPO,
              sEO: row.sEO,
              imageUrl: row.imageUrl,
              IsModify: 0
          )
      );
    }
  }

  // Below are my Database methods

  Future<int> deleteImportedShops(int shopID, String updatedDate) async{
    Database db = await instance.database;
    return await db.delete("$shopsTable", where: 'ShopID = ? AND UpdatedOn <= ?', whereArgs: [shopID, updatedDate]);
  }

  Future<void> insertShops(ShopsModel shopsRow) async{
    Database db = await instance.database;
    await db.transaction((txn) async {
      var batch = txn.batch();
      batch.insert("$shopsTable", shopsRow.toJson(), conflictAlgorithm: ConflictAlgorithm.replace);
      await batch.commit();
    });
  }

  Future<void> insertSyncDataHistory(SyncDataModel row) async{
    Database db = await instance.database;
    await db.transaction((txn) async {
      var batch = txn.batch();
      batch.insert("$syncDataTable", row.toJson(), conflictAlgorithm: ConflictAlgorithm.replace);
      await batch.commit();
    });
  }

  Future<void> updateShopSyncDate(String? pDate, int id) async{
    Database db = await instance.database;
    await db.transaction((txn) async {
      var batch = txn.batch();
      batch.rawUpdate("UPDATE SyncDataHistory SET ShopSyncDate = ?, LastSyncDate = ? WHERE SyncID = ?", [pDate, pDate, id]);
      await batch.commit();
    });
  }

以下是我作为输出得到的详细信息。警告数据库已锁定0:00:10.000000。确保在事务期间始终使用事务对象进行数据库操作
请帮帮我任何帮助将不胜感激。

lf3rwulv

lf3rwulv1#

我正在调查这个问题,我发现sqflite库在并发方面有一些问题(一般来说):
https://github.com/tekartik/sqflite/issues/988
该问题表明,当您生成bach.insert(...)时,数据库完全锁定。
一个坏消息是应用程序可能会崩溃,另一个是问题仍然是打开
所以,现在没有办法!
我正在使用:
sqflite:^2.2.8

相关问题