insertOrUpdate method

Future<int> insertOrUpdate(
  1. Database db, {
  2. Logger? logger,
})

If the request already exists in the database, increment attemps and set updated_at to current time.

Implementation

Future<int> insertOrUpdate(Database db, {Logger? logger}) async {
  final response = await findRequestInDatabase(db);

  return db.transaction((txn) async {
    if (response == null || response.isEmpty) {
      final serialized = toSqlite();
      serialized[lockedColumn] = 1;

      logger?.fine('adding to queue: $serialized');
      return await txn.insert(
        tableName,
        serialized,
      );
    }

    logger?.warning('failed, attempt #${response[attemptColumn]} ${attemptLogMessage(response)}');

    return await txn.update(
      tableName,
      {
        attemptColumn: response[attemptColumn] + 1,
        updateAtColumn: DateTime.now().millisecondsSinceEpoch,
        lockedColumn: 1,
      },
      where: '$primaryKeyColumn = ?',
      whereArgs: [response[primaryKeyColumn]],
    );
  });
}