insertOne method

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

Implementation

@override
Future<int> insertOne({required T entity, Database? database}) async {
  Map<String, dynamic> data = this
      .sanitizeIncomingData(entity: entity.toJson(), columns: this.columns);
  final Database db = database != null ? database : this.database;

  int saveDataResponse = 0;
  try {
    saveDataResponse = await db.insert(this.entity.tableName, data);
  } catch (e) {}

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

  final reltionQueue = Queue(parallel: 1);
  num availableItemCount = 0;

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

            reltionQueue.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) {
          reltionQueue.add(() => saveRelationData(
              columnRelation: column.relation as ColumnRelation,
              entity: classMirror.newInstance('fromJson', [dataItem]) as T,
              database: db));
        });
      }
    });
  }

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

  await reltionQueue.onComplete;
  return saveDataResponse;
}