main
 1import 'package:sqflite_common/sqflite.dart';
 2
 3/// Helper methods for database interaction to allow code reuse.
 4class DBHelper {
 5  DBHelper._();
 6
 7  /// Get a entryID from the `Timestamps` table of a database.
 8  ///
 9  /// Ensures that the associated timestamp matches [timestampUnixS]. Creates a
10  /// new id when necessary.
11  static Future<int> getEntryID(
12    Transaction txn,
13    int timestampUnixS,
14  ) async {
15    final existing = await txn.rawQuery(
16      'SELECT entryID FROM Timestamps WHERE timestampUnixS = ?',
17      [timestampUnixS],
18    );
19    int entryID;
20    if (existing.isEmpty) {
21      final result = await txn.query('Timestamps', columns: ['MAX(entryID)']);
22      final highestID = result.first['MAX(entryID)'] as int?;
23      entryID = (highestID ?? 0) + 1;
24      await txn.insert('Timestamps', {
25        'entryID': entryID,
26        'timestampUnixS': timestampUnixS,
27      });
28    } else {
29      entryID = existing.first['entryID'] as int;
30    }
31    return entryID;
32  }
33}