batchInsertOrUpdate method

Future<int> batchInsertOrUpdate({
  1. @required required List objects,
})

Performs a batch insert or update operation on a table.

This method takes a list of objects as a parameter and performs a batch insert or update 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 objects.

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 also calls the _getIntersectionList method with these two sets as parameters to get a list of existing objects that need to be updated in the table.

It then performs a batch insert operation with the new objects and a batch update operation with the existing objects. The total number of rows affected by these operations is returned.

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

Usage:

var objects = [object1, object2, object3];
int result = await daoConnector.batchInsertOrUpdate(objects: objects);
print('Number of rows affected: $result');

Implementation

Future<int> batchInsertOrUpdate(
    {@required required List<dynamic> objects}) async {
  int result;
  var queryResult = await select(
      sqlBuilder: SqlBuilder()
          .querySelect()
          .queryFrom(table: getTableName(objects.first)),
      model: objects.first,
      print: false);

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

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

  List<dynamic> intersectionList =
      _getIntersectionList(objectsToInsertSet, querySet);

  result = await batchInsert(objectsToInsert: differenceList);
  result += await batchUpdate(objectsToUpdate: intersectionList);

  return result;
}