upsert method

Future<SessionData> upsert(
  1. UserId userId, {
  2. NewType<FavoriteChatsListVersion?>? favoriteChatsListVersion,
  3. NewType<bool?>? favoriteChatsSynchronized,
  4. NewType<ChatContactsListVersion?>? chatContactsListVersion,
  5. NewType<bool?>? favoriteContactsSynchronized,
  6. NewType<bool?>? contactsSynchronized,
  7. NewType<bool?>? blocklistSynchronized,
  8. NewType<SessionsListVersion?>? sessionsListVersion,
  9. NewType<BlocklistVersion?>? blocklistVersion,
  10. NewType<int?>? blocklistCount,
})

Creates or updates the provided data in the database.

Implementation

Future<SessionData> upsert(
  UserId userId, {
  NewType<FavoriteChatsListVersion?>? favoriteChatsListVersion,
  NewType<bool?>? favoriteChatsSynchronized,
  NewType<ChatContactsListVersion?>? chatContactsListVersion,
  NewType<bool?>? favoriteContactsSynchronized,
  NewType<bool?>? contactsSynchronized,
  NewType<bool?>? blocklistSynchronized,
  NewType<SessionsListVersion?>? sessionsListVersion,
  NewType<BlocklistVersion?>? blocklistVersion,
  NewType<int?>? blocklistCount,
}) async {
  final SessionData? existing = data[userId];
  final SessionData session = (existing ?? SessionData()).replaceWith(
    favoriteChatsListVersion: favoriteChatsListVersion,
    favoriteChatsSynchronized: favoriteChatsSynchronized,
    chatContactsListVersion: chatContactsListVersion,
    favoriteContactsSynchronized: favoriteContactsSynchronized,
    contactsSynchronized: contactsSynchronized,
    blocklistSynchronized: blocklistSynchronized,
    sessionsListVersion: sessionsListVersion,
    blocklistVersion: blocklistVersion,
    blocklistCount: blocklistCount,
  );

  data[userId] = session;

  final result = await safe((db) async {
    try {
      return _SessionDataDb.fromDb(
        await db
            .into(db.versions)
            .insertReturning(session.toDb(userId), mode: InsertMode.replace),
      );
    } on DriftRemoteException {
      // Upsert may fail during E2E tests due to rapid database resetting and
      // creating.
      return null;
    }
  });

  return result ?? session;
}