saveRelationData method
Future
saveRelationData({
- required ColumnRelation columnRelation,
- required BaseEntity entity,
- Database? database,
Implementation
Future saveRelationData(
{required ColumnRelation columnRelation,
required BaseEntity entity,
Database? database}) async {
Map<String, dynamic> data = this.sanitizeIncomingData(
entity: entity.toJson(),
columns: columnRelation.referencedEntityColumns as List<Column>);
final Database db = database != null ? database : this.database;
var result = await db.query(
columnRelation.referencedEntity?.tableName as String,
where: 'id = ?',
whereArgs: [data['id']]);
dynamic saveDataResponse;
if (result.length == 0) {
try {
saveDataResponse = await db.insert(
columnRelation.referencedEntity?.tableName as String, data);
} catch (e) {}
} else {
final lastUpdated = result[0]['lastUpdated'];
if (lastUpdated != null) {
final currentLastUpdatedDate = DateTime.parse(lastUpdated as String);
final newLastUpdatedDate = DateTime.parse(
data['lastUpdated'] ?? DateTime.now().toIso8601String());
if (currentLastUpdatedDate
.difference(newLastUpdatedDate)
.inMilliseconds >
0) {
saveDataResponse = 1;
} else {
if (data['dirty'] == 1) {
data['lastUpdated'] = DateTime.now().toIso8601String();
}
saveDataResponse = await db.update(
columnRelation.referencedEntity?.tableName as String,
data,
where: "id = ?",
whereArgs: [data['id']],
);
}
} else {
saveDataResponse = 1;
}
}
final List<Column?>? oneToManyColumns = columnRelation
.referencedEntityColumns
?.where((column) =>
column?.relation?.relationType == RelationType.OneToMany)
.toList();
if (oneToManyColumns!.isEmpty) {
return saveDataResponse;
}
final queue = Queue(parallel: 50);
num availableItemCount = 0;
oneToManyColumns.forEach((Column? column) {
final List data = entity.toJson()[column?.relation?.attributeName];
if (data.isNotEmpty) {
availableItemCount++;
data.forEach((dataItem) {
queue.add(() => saveRelationData(
columnRelation: column?.relation as ColumnRelation,
entity: dataItem,
database: db));
});
}
});
if (availableItemCount == 0) {
queue.cancel();
return saveDataResponse;
}
await queue.onComplete;
return saveDataResponse;
}