Simplify DB upgrade

This commit is contained in:
Ming Ming 2021-06-15 17:24:38 +08:00
parent fd95e459b8
commit 9297686a6e

View file

@ -45,34 +45,31 @@ class AppDb {
final db = event.database; final db = event.database;
ObjectStore fileStore, albumStore, fileDbStore; ObjectStore fileStore, albumStore, fileDbStore;
if (event.oldVersion < 1) {
fileStore = db.createObjectStore(fileStoreName);
albumStore = db.createObjectStore(albumStoreName);
} else {
fileStore = event.transaction.objectStore(fileStoreName);
albumStore = event.transaction.objectStore(albumStoreName);
}
if (event.oldVersion < 2) { if (event.oldVersion < 2) {
// version 2 store things in a new way, just drop all // version 2 store things in a new way, just drop all
await fileStore.clear(); try {
await albumStore.clear(); db.deleteObjectStore(albumStoreName);
fileStore.createIndex(AppDbFileEntry.indexName, AppDbFileEntry.keyPath); } catch (_) {}
albumStore = db.createObjectStore(albumStoreName);
albumStore.createIndex( albumStore.createIndex(
AppDbAlbumEntry.indexName, AppDbAlbumEntry.keyPath); AppDbAlbumEntry.indexName, AppDbAlbumEntry.keyPath);
} }
if (event.oldVersion < 3) { if (event.oldVersion < 3) {
// new object store in v3 // new object store in v3
try {
db.deleteObjectStore(fileDbStoreName);
} catch (_) {}
fileDbStore = db.createObjectStore(fileDbStoreName); fileDbStore = db.createObjectStore(fileDbStoreName);
fileDbStore.createIndex( fileDbStore.createIndex(
AppDbFileDbEntry.indexName, AppDbFileDbEntry.keyPath, AppDbFileDbEntry.indexName, AppDbFileDbEntry.keyPath,
unique: false); unique: false);
// drop files // recreate file store from scratch
// ObjectStore.clear is bugged when there's index created on Android try {
final cursor = fileStore.openKeyCursor(autoAdvance: true); db.deleteObjectStore(fileStoreName);
await for (final k in cursor) { } catch (_) {}
await fileStore.delete(k.primaryKey); fileStore = db.createObjectStore(fileStoreName);
} fileStore.createIndex(AppDbFileEntry.indexName, AppDbFileEntry.keyPath);
} }
}); });
} }