mutate method

Future<TDao> mutate(
  1. TPrimaryKey id,
  2. FutureOr<TDao> mutator(
    1. TDao
    )
)

Query, modify and update an entry in a single transaction.

The entry with primary key id will be selected and passed through mutator. The object that is returned by mutator is then updated on the database.

It is not allowed to change the primary key inside of mutator. An exception will be thrown otherwise.

Implementation

Future<TDao> mutate(
    TPrimaryKey id, FutureOr<TDao> Function(TDao) mutator) async {
  return await transaction(
    (context) async {
      final object = await context.queryId(bean, id);
      if (object != null) {
        final updated = await mutator(object);
        if (updated.getPrimaryKey() != id) {
          throw PersistenceException('Mutator modified primary key.');
        }
        await context.update(updated);
        return updated;
      } else {
        throw PersistenceException('Object with id "$id" not found.');
      }
    },
  );
}