addOrUpdate method
Adds or updates the given items
in the local database.
If fromCloud
is true, it indicates that the items
are being synced from the cloud.
Implementation
@override
Future<void> addOrUpdate(List<T> items, {bool fromCloud = false}) async {
final db = database;
await db.transaction((txn) async {
for (final item in items) {
try {
final existingItemResult = await txn.query(
tableName,
where: 'id = ?',
whereArgs: [item.id],
limit: 1,
);
if (existingItemResult.isEmpty) {
await txn.insert(
tableName,
item
.copyWith(
localTimeSyncedAt: fromCloud ? DateTime.now() : null)
.toJson(),
);
} else {
final existingItem = fromJson(existingItemResult.first);
// Sync logic: Update if item is newer or from the cloud
if (fromCloud || item.updatedAt!.isAfter(existingItem.updatedAt!)) {
await txn.update(
tableName,
item.copyWith(localTimeSyncedAt: DateTime.now()).toJson(),
where: 'id = ?',
whereArgs: [item.id],
);
}
}
} catch (e) {
_logger.e('Error processing item ${item.id}: $e');
}
}
});
}