batchInsert method

Future<int> batchInsert({
  1. @required required List objectsToInsert,
  2. bool orUpdate = false,
})

Performs a batch insert operation on a table.

This method takes a list of objectsToInsert as a parameter and performs a batch insert operation. It first performs a select operation on the table corresponding to the type of the first object in the list. It then creates two sets: one from the result of the select operation and another from the input objectsToInsert.

It calls the _getDifferenceList method with these two sets as parameters to get a list of new objects that need to be inserted into the table.

It then performs a batch insert operation with the new objects. The total number of rows affected by this operation is returned.

This method is useful when you have a list of objects and you want to insert new objects into the table in a single operation.

Usage:

var objectsToInsert = [object1, object2, object3];
int result = await daoConnector.batchInsert(objectsToInsert: objectsToInsert);
print('Number of rows inserted: $result');

Implementation

Future<int> batchInsert(
    {@required required List<dynamic> objectsToInsert,
    bool orUpdate = false}) async {
  var db = await getDatabase();
  var batch = db!.batch();

  var queryResult = await select(
      sqlBuilder: SqlBuilder()
          .querySelect()
          .queryFrom(table: getTableName(objectsToInsert.first)),
      model: objectsToInsert.first,
      print: false);

  Set<dynamic> querySet = Set.of(queryResult);
  Set<dynamic> objectsToInsertSet = Set.of(objectsToInsert);

  List<dynamic> differenceList =
      _getDifferenceList(objectsToInsertSet, querySet);

  for (var object in differenceList) {
    batch.insert(getTableName(object), object.toJson());
  }
  try {
    var result = await batch.commit();
    return result.length;
  } catch (e) {
    PrintHandler.warningLogger.e(
        '⛔sqflite_simple_dao_backend⛔: Error inserting batch: $e. "-1" returned.');
    return -1;
  }
}