updateSingle method

Future<int> updateSingle({
  1. @required required dynamic objectToUpdate,
})

This method is used to update a single object in the database.

It takes an object as a parameter and updates the corresponding record in the database. If the update operation is successful, the method returns the number of rows affected. If an error occurs during the update operation, the method logs the error and returns -1.

The method first gets the database instance. Then, it uses reflection to get the primary key(s) of the object. It constructs a WHERE clause for the update operation using the primary key(s) and their values.

Then, it updates the corresponding record in the database. The table name for the update operation is obtained by calling the getTableName method with the object. The new values for the record are obtained by calling the toJson method on the object.

Parameters: objectToUpdate (dynamic): The object to update in the database.

Returns: Future

Implementation

Future<int> updateSingle({@required required dynamic objectToUpdate}) async {
  var db = await getDatabase();

  InstanceMirror reflectNew = reflector.reflect(objectToUpdate);
  List<String> primary =
      reflectNew.type.invokeGetter("primary") as List<String>;
  List<dynamic> databaseModel;

  databaseModel = 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 = {};

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

  if (updatedFields.isEmpty) {
    PrintHandler.warningLogger.w(
        '⚠️sqflite_simple_dao_backend⚠️: No changes detected. "0" returned.');
    return 0;
  }

  String where = primary.map((e) => '$e = ?').join(' AND ');
  List<dynamic> whereArgs =
      primary.map((e) => reflectNew.invokeGetter(e)).toList();

  int result = await db!.update(
    getTableName(objectToUpdate),
    updatedFields,
    where: where,
    whereArgs: whereArgs,
  );

  return result;
}