batchUpdate method

Future<int> batchUpdate({
  1. @required required List objectsToUpdate,
})

This method is used to update a list of objects in the database.

It takes a list of objects as a parameter and updates each object in the database in a batch operation. This can improve performance when updating multiple objects at once.

The method first gets the database instance and starts a batch operation. Then, for each object in the list, it calls the toJson method on the object to convert it to a map, and updates the corresponding record in the database. The table name for the update operation is obtained by calling the getTableName method with the object.

After all objects have been updated, the batch operation is committed and the method returns the number of operations that were performed. If an error occurs during the batch operation, the method logs the error and returns -1.

Parameters: objectsToUpdate (List

Returns: Future

Implementation

Future<int> batchUpdate(
    {@required required List<dynamic> objectsToUpdate}) async {
  var db = await getDatabase();
  var batch = db!.batch();

  for (var objectToUpdate in objectsToUpdate) {
    InstanceMirror reflectNew = reflector.reflect(objectToUpdate);
    List<String> primary =
        reflectNew.type.invokeGetter("primary") as List<String>;
    dynamic existingObject = await select<dynamic>(
        sqlBuilder: SqlBuilder()
            .querySelect()
            .queryFrom(table: getTableName(objectToUpdate))
            .queryWhere(
                conditions: primary
                    .map((e) => '$e = ${reflectNew.invokeGetter(e)}')
                    .toList()),
        model: objectToUpdate,
        print: false);

    Map<String, dynamic> updatedFields = {};
    var whereArgs = [];

    for (String field in objectToUpdate.toJson().keys) {
      if (objectToUpdate.toJson()[field] !=
          existingObject[0].toJson()[field]) {
        updatedFields[field] = objectToUpdate.toJson()[field];
      }
    }

    if (updatedFields.isEmpty) {
      continue;
    }
    String where = '';
    // Primary keys
    for (var x in primary) {
      whereArgs.add(reflectNew.invokeGetter(x));

      where = makeWhere(where, x, primary);
    }

    batch.update(getTableName(objectToUpdate), updatedFields,
        where: where, whereArgs: whereArgs);
  }
  try {
    var result = await batch.commit();
    return result.length;
  } catch (e) {
    PrintHandler.warningLogger.e(
        '⛔sqflite_simple_dao_backend⛔: Error updating batch: $e. "-1" returned.');
    return -1;
  }
}