batchDelete method
Performs a batch delete operation on a table.
This method takes a list of objectsToDelete as a parameter and performs a batch delete operation.
It first gets the database instance and starts a batch operation.
Then, for each object in the list of objects to delete, it uses reflection to get
the primary key(s) of the object. It constructs a WHERE clause for the delete
operation using the primary key(s) and their values.
It then adds the delete operation to the batch. The table name for the delete operation
is obtained by calling the getTableName method with the object.
Finally, it commits the batch and returns the number of operations in the batch. If an error occurs during the delete operation, the method logs the error and returns -1.
This method is useful when you have a list of objects and you want to delete them from the table in a single operation.
Usage:
var objectsToDelete = [object1, object2, object3];
int result = await daoConnector.batchDelete(objectsToDelete: objectsToDelete);
print('Number of rows deleted: $result');
Implementation
Future<int> batchDelete(
{@required required List<dynamic> objectsToDelete}) async {
var db = await getDatabase();
var batch = db!.batch();
for (var object in objectsToDelete) {
InstanceMirror reflectNew = reflector.reflect(object);
List<String> primary =
reflectNew.type.invokeGetter("primary") as List<String>;
List<dynamic> whereArgs = [];
/* Construct the WHERE clause. */
String where = '';
// Primary keys
for (var x in primary) {
whereArgs.add(reflectNew.invokeGetter(x));
where = makeWhere(where, x, primary);
}
batch.delete(getTableName(object), where: where, whereArgs: whereArgs);
}
try {
var result = await batch.commit();
return result.length;
} catch (e) {
PrintHandler.warningLogger.e(
'⛔sqflite_simple_dao_backend⛔: Error deleting batch: $e. "-1" returned.');
return -1;
}
}