save method

Future<void> save()

Persists the model to storage (Upsert logic).

Flow:

  1. Trigger onSaving.
  2. If new (exists is false): perform INSERT.
  3. If existing: Calculate diff (dirtyAttributes) and UPDATE only changed fields.
  4. Refresh: Re-fetch record to sync DB-generated values (autoincrement IDs, timestamps, triggers).
  5. 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();
}