[mob][photos] Add schema migration easier on FaceMLDataDB

This commit is contained in:
ashilkn 2024-05-27 12:56:20 +05:30
parent baa90c42ad
commit ee8976e92b

View file

@ -35,6 +35,15 @@ class FaceMLDataDB {
static final FaceMLDataDB instance = FaceMLDataDB._privateConstructor(); static final FaceMLDataDB instance = FaceMLDataDB._privateConstructor();
static final _migrationScripts = [
createFacesTable,
createFaceClustersTable,
createClusterPersonTable,
createClusterSummaryTable,
createNotPersonFeedbackTable,
fcClusterIDIndex,
];
// only have a single app-wide reference to the database // only have a single app-wide reference to the database
static Future<SqliteDatabase>? _sqliteAsyncDBFuture; static Future<SqliteDatabase>? _sqliteAsyncDBFuture;
@ -50,25 +59,30 @@ class FaceMLDataDB {
_logger.info("Opening sqlite_async access: DB path " + databaseDirectory); _logger.info("Opening sqlite_async access: DB path " + databaseDirectory);
final asyncDBConnection = final asyncDBConnection =
SqliteDatabase(path: databaseDirectory, maxReaders: 2); SqliteDatabase(path: databaseDirectory, maxReaders: 2);
await _onCreate(asyncDBConnection); await _migrate(asyncDBConnection);
return asyncDBConnection; return asyncDBConnection;
} }
Future<void> _onCreate(SqliteDatabase asyncDBConnection) async { Future<void> _migrate(
try { SqliteDatabase database,
final startTime = DateTime.now(); ) async {
await asyncDBConnection.execute(createFacesTable); final result = await database.execute('PRAGMA user_version');
await asyncDBConnection.execute(createFaceClustersTable); final currentVersion = result[0]['user_version'] as int;
await asyncDBConnection.execute(createClusterPersonTable); final toVersion = _migrationScripts.length;
await asyncDBConnection.execute(createClusterSummaryTable);
await asyncDBConnection.execute(createNotPersonFeedbackTable); if (currentVersion < toVersion) {
await asyncDBConnection.execute(fcClusterIDIndex); _logger.info("Migrating database from $currentVersion to $toVersion");
_logger.info( await database.writeTransaction((tx) async {
'FaceMLDataDB tables created in ${DateTime.now().difference(startTime).inMilliseconds}ms', for (int i = currentVersion + 1; i <= toVersion; i++) {
await tx.execute(_migrationScripts[i - 1]);
}
await tx.execute('PRAGMA user_version = $toVersion');
});
} else if (currentVersion > toVersion) {
throw AssertionError(
"currentVersion($currentVersion) cannot be greater than toVersion($toVersion)",
); );
} catch (e, s) {
_logger.severe("Error creating FaceMLDataDB tables", e, s);
rethrow;
} }
} }