open method
Open the database, apply PRAGMAs, create table if needed.
Implementation
Future<bool> open() async {
try {
final dbPath = await getDatabasesPath();
final fullPath = p.join(dbPath, _dbName);
_db = await openDatabase(
fullPath,
version: 2,
onCreate: (db, version) async {
await db.execute('''
CREATE TABLE $_tableName (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts_millis INTEGER NOT NULL,
event_name TEXT NOT NULL,
payload_json TEXT NOT NULL
)
''');
await db.execute('CREATE INDEX idx_ts ON $_tableName (ts_millis)');
await db.execute(
'CREATE INDEX idx_event_name ON $_tableName (event_name)',
);
await _createLegacyMigrationJournalTable(db);
},
onUpgrade: (db, oldVersion, newVersion) async {
if (oldVersion < 2) {
await _createLegacyMigrationJournalTable(db);
}
},
);
// Apply PRAGMAs for durability and performance
await _db!.rawQuery('PRAGMA journal_mode=WAL');
await _db!.rawQuery('PRAGMA synchronous=NORMAL');
await _db!.rawQuery('PRAGMA busy_timeout=3000');
_isOpen = true;
return true;
} catch (e, st) {
dbLogger.severe('SqliteEventStorage: open failed', e, st);
_isOpen = false;
if (isLikelyCorruptionError(e)) {
final deletedAnyFiles = await _tryRecoverCorruptedDb();
if (deletedAnyFiles) {
_destructiveRecoveryDetected = true;
}
}
return false;
}
}