upsert method

Future<SessionData> upsert(
  1. UserId userId,
  2. SessionData data
)

Creates or updates the provided data in the database.

Implementation

Future<SessionData> upsert(UserId userId, SessionData data) async {
  final SessionData? existing = this.data[userId];
  this.data[userId] = (existing ?? SessionData()).copyFrom(data);

  final result = await safe((db) async {
    try {
      final SessionData stored = _SessionDataDb.fromDb(
        await db
            .into(db.versions)
            .insertReturning(
              data.toDb(userId),
              onConflict: DoUpdate((_) => data.toDb(userId)),
            ),
      );

      return stored;
    } on DriftRemoteException {
      // Upsert may fail during E2E tests due to rapid database resetting and
      // creating.
      return null;
    }
  });

  return result ?? data;
}