updateOne method

  1. @override
Future<int> updateOne({
  1. required T entity,
  2. Database? database,
})
override

Implementation

@override
Future<int> updateOne({required T entity, Database? database}) async {
  if (entity.dirty == true && entity.lastUpdated == null) {
    entity.lastUpdated = DateTime.now().toIso8601String();
  }
  Map<String, dynamic> data = this
      .sanitizeIncomingData(entity: entity.toJson(), columns: this.columns);

  final Database db = database != null ? database : this.database;
  final saveDataResponse = await db.update(
    this.entity.tableName,
    data,
    where: "id = ?",
    whereArgs: [data['id']],
  );

  if (this.oneToManyColumns.isEmpty) {
    return saveDataResponse;
  }

  final queue = Queue(parallel: 50);
  num availableItemCount = 0;

  try {
    this.oneToManyColumns.forEach((Column column) {
      final List data = entity.toJson()[column.relation?.attributeName] ?? [];
      ClassMirror classMirror =
          AnnotationReflectable.reflectType(T) as ClassMirror;
      if (data.isNotEmpty) {
        availableItemCount++;
        data.forEach((dataItem) {
          try {
            queue.add(() => saveRelationData(
                columnRelation: column.relation as ColumnRelation,
                entity: dataItem,
                database: db));
          } catch (e) {
            queue.add(() => saveRelationData(
                columnRelation: column.relation as ColumnRelation,
                entity: classMirror.newInstance('fromJson', [dataItem]) as T,
                database: db));
          }
        });
      }
    });
  } catch (e) {
    this.oneToManyColumns.forEach((Column column) {
      final List data = entity.toJson()[column.relation?.attributeName] ?? [];
      ClassMirror classMirror =
          AnnotationReflectable.reflectType(T) as ClassMirror;

      if (data.isNotEmpty) {
        availableItemCount++;
        data.forEach((dataItem) {
          queue.add(() => saveRelationData(
              columnRelation: column.relation as ColumnRelation,
              entity: classMirror.newInstance('fromJson', [dataItem]) as T,
              database: db));
        });
      }
    });
  }

  if (availableItemCount == 0) {
    queue.cancel();
    return saveDataResponse;
  }

  await queue.onComplete;
  return saveDataResponse;
}