save method

Future<bool> save()
inherited

Save the model to the database.

Implementation

Future<bool> save() async {
  final query = this.query;

  // If the model already exists
  if (exists) {
    // Check if dirty
    if (this is HasAttributes) {
      final dirty = (this as HasAttributes).getDirty();
      if (dirty.isEmpty) return true;
    }

    if (this is HasEvents) {
      if (await (this as HasEvents).fireModelEvent(ModelLifecycle.updating) ==
          false) {
        return false;
      }
      if (await (this as HasEvents).fireModelEvent(ModelLifecycle.saving) ==
          false) {
        return false;
      }
    }

    // Perform Update
    if (this is HasAttributes) {
      final dirty = (this as HasAttributes).getDirty();
      final updateData = <String, dynamic>{};

      final dbMap = (this as HasAttributes).toDatabaseMap();
      for (var key in dirty.keys) {
        if (dbMap.containsKey(key)) {
          updateData[key] = dbMap[key];
        }
      }

      if (updateData.isNotEmpty) {
        await query.where(primaryKey, '=', getKey()).update(updateData);
      }
    }

    if (this is HasEvents) {
      await (this as HasEvents)
          .fireModelEvent(ModelLifecycle.updated, halt: false);
      await (this as HasEvents)
          .fireModelEvent(ModelLifecycle.saved, halt: false);
    }

    if (this is HasAttributes) {
      (this as HasAttributes).syncOriginal();
    }
  }
  // If the model is new
  else {
    if (this is HasEvents) {
      if (await (this as HasEvents).fireModelEvent(ModelLifecycle.creating) ==
          false) {
        return false;
      }
      if (await (this as HasEvents).fireModelEvent(ModelLifecycle.saving) ==
          false) {
        return false;
      }
    }

    // Perform Insert
    if (this is HasAttributes) {
      final data = (this as HasAttributes).toDatabaseMap();
      final insertId = await query.insert(data);

      // Set ID
      if (primaryKey == 'id') {
        this.id = insertId;
        (this as HasAttributes).setAttribute('id', insertId);
      }
    }

    if (this is HasEvents) {
      await (this as HasEvents)
          .fireModelEvent(ModelLifecycle.created, halt: false);
      await (this as HasEvents)
          .fireModelEvent(ModelLifecycle.saved, halt: false);
    }

    if (this is HasAttributes) {
      (this as HasAttributes).syncOriginal();
    }

    exists = true;
  }

  return true;
}