save method
Persists the model to storage (Upsert logic).
Flow:
- Trigger
onSaving. - If new (exists is false): perform INSERT.
- If existing: Calculate diff (
dirtyAttributes) and UPDATE only changed fields. - Refresh: Re-fetch record to sync DB-generated values (autoincrement IDs, timestamps, triggers).
- Trigger
onSaved.
Implementation
Future<void> save() async {
if (!await onSaving()) return;
final dbManager = DatabaseManager();
final dataToSave = dehydrateAttributes();
if (!exists) {
final insertId = await dbManager.insert(table, dataToSave);
id ??= insertId;
exists = true;
} else {
// Dirty Checking: identify strictly changed values to optimize the SQL payload.
final dirtyAttributes = <String, dynamic>{};
dataToSave.forEach((key, value) {
if (key != primaryKey && value != original[key]) {
dirtyAttributes[key] = value;
}
});
if (dirtyAttributes.isEmpty) {
return;
}
await query().where(primaryKey, id).update(dirtyAttributes);
}
await refresh();
await onSaved();
}