summaryrefslogtreecommitdiff
path: root/lib/model/db
diff options
context:
space:
mode:
Diffstat (limited to 'lib/model/db')
-rw-r--r--lib/model/db/db.dart136
-rw-r--r--lib/model/db/db_extension.dart13
-rw-r--r--lib/model/db/db_sqflite.dart704
-rw-r--r--lib/model/db/db_sqflite_schema.dart118
-rw-r--r--lib/model/db/db_sqflite_upgrade.dart503
5 files changed, 1474 insertions, 0 deletions
diff --git a/lib/model/db/db.dart b/lib/model/db/db.dart
new file mode 100644
index 0000000..c7e7820
--- /dev/null
+++ b/lib/model/db/db.dart
@@ -0,0 +1,136 @@
+import 'package:aves/model/covers.dart';
+import 'package:aves/model/dynamic_albums.dart';
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves/model/favourites.dart';
+import 'package:aves/model/filters/filters.dart';
+import 'package:aves/model/metadata/address.dart';
+import 'package:aves/model/metadata/catalog.dart';
+import 'package:aves/model/metadata/trash.dart';
+import 'package:aves/model/vaults/details.dart';
+import 'package:aves/model/viewer/video_playback.dart';
+
+abstract class LocalMediaDb {
+ int get nextId;
+
+ Future<String> get path;
+
+ Future<void> init();
+
+ Future<int> dbFileSize();
+
+ Future<void> reset();
+
+ Future<void> removeIds(Set<int> ids, {Set<EntryDataType>? dataTypes});
+
+ // entries
+
+ Future<void> clearEntries();
+
+ Future<Set<AvesEntry>> loadEntries({int? origin, String? directory});
+
+ Future<Set<AvesEntry>> loadEntriesById(Set<int> ids);
+
+ Future<void> insertEntries(Set<AvesEntry> entries);
+
+ Future<void> updateEntry(int id, AvesEntry entry);
+
+ Future<Set<AvesEntry>> searchLiveEntries(String query, {int? limit});
+
+ Future<Set<AvesEntry>> searchLiveDuplicates(int origin, Set<AvesEntry>? entries);
+
+ // date taken
+
+ Future<void> clearDates();
+
+ Future<Map<int?, int?>> loadDates();
+
+ // catalog metadata
+
+ Future<void> clearCatalogMetadata();
+
+ Future<Set<CatalogMetadata>> loadCatalogMetadata();
+
+ Future<Set<CatalogMetadata>> loadCatalogMetadataById(Set<int> ids);
+
+ Future<void> saveCatalogMetadata(Set<CatalogMetadata> metadataEntries);
+
+ Future<void> updateCatalogMetadata(int id, CatalogMetadata? metadata);
+
+ // address
+
+ Future<void> clearAddresses();
+
+ Future<Set<AddressDetails>> loadAddresses();
+
+ Future<Set<AddressDetails>> loadAddressesById(Set<int> ids);
+
+ Future<void> saveAddresses(Set<AddressDetails> addresses);
+
+ Future<void> updateAddress(int id, AddressDetails? address);
+
+ // vaults
+
+ Future<void> clearVaults();
+
+ Future<Set<VaultDetails>> loadAllVaults();
+
+ Future<void> addVaults(Set<VaultDetails> rows);
+
+ Future<void> updateVault(String oldName, VaultDetails row);
+
+ Future<void> removeVaults(Set<VaultDetails> rows);
+
+ // trash
+
+ Future<void> clearTrashDetails();
+
+ Future<Set<TrashDetails>> loadAllTrashDetails();
+
+ Future<void> updateTrash(int id, TrashDetails? details);
+
+ // favourites
+
+ Future<void> clearFavourites();
+
+ Future<Set<FavouriteRow>> loadAllFavourites();
+
+ Future<void> addFavourites(Set<FavouriteRow> rows);
+
+ Future<void> updateFavouriteId(int id, FavouriteRow row);
+
+ Future<void> removeFavourites(Set<FavouriteRow> rows);
+
+ // covers
+
+ Future<void> clearCovers();
+
+ Future<Set<CoverRow>> loadAllCovers();
+
+ Future<void> addCovers(Set<CoverRow> rows);
+
+ Future<void> updateCoverEntryId(int id, CoverRow row);
+
+ Future<void> removeCovers(Set<CollectionFilter> filters);
+
+ // dynamic albums
+
+ Future<int> clearDynamicAlbums();
+
+ Future<Set<DynamicAlbumRow>> loadAllDynamicAlbums();
+
+ Future<void> addDynamicAlbums(Set<DynamicAlbumRow> rows);
+
+ Future<void> removeDynamicAlbums(Set<String> names);
+
+ // video playback
+
+ Future<void> clearVideoPlayback();
+
+ Future<Set<VideoPlaybackRow>> loadAllVideoPlayback();
+
+ Future<VideoPlaybackRow?> loadVideoPlayback(int id);
+
+ Future<void> addVideoPlayback(Set<VideoPlaybackRow> rows);
+
+ Future<void> removeVideoPlayback(Set<int> ids);
+}
diff --git a/lib/model/db/db_extension.dart b/lib/model/db/db_extension.dart
new file mode 100644
index 0000000..a0d2a66
--- /dev/null
+++ b/lib/model/db/db_extension.dart
@@ -0,0 +1,13 @@
+import 'package:sqflite/sqflite.dart';
+
+extension ExtraDatabase on Database {
+ // check table existence via `sqlite_master`
+ // `sqlite_schema` is the alias used in SQLite documentation,
+ // but it was introduced in SQLite v3.33.0 and it is unavailable on Android API < 34,
+ // and the historical alias `sqlite_master` is still supported.
+ // cf https://www.sqlite.org/faq.html#q7
+ Future<bool> tableExists(String table) async {
+ final results = await query('sqlite_master', where: 'type = ? AND name = ?', whereArgs: ['table', table]);
+ return results.isNotEmpty;
+ }
+}
diff --git a/lib/model/db/db_sqflite.dart b/lib/model/db/db_sqflite.dart
new file mode 100644
index 0000000..6d44421
--- /dev/null
+++ b/lib/model/db/db_sqflite.dart
@@ -0,0 +1,704 @@
+import 'dart:io';
+
+import 'package:aves/model/covers.dart';
+import 'package:aves/model/db/db.dart';
+import 'package:aves/model/db/db_sqflite_schema.dart';
+import 'package:aves/model/db/db_sqflite_upgrade.dart';
+import 'package:aves/model/dynamic_albums.dart';
+import 'package:aves/model/entry/entry.dart';
+import 'package:aves/model/favourites.dart';
+import 'package:aves/model/filters/filters.dart';
+import 'package:aves/model/metadata/address.dart';
+import 'package:aves/model/metadata/catalog.dart';
+import 'package:aves/model/metadata/trash.dart';
+import 'package:aves/model/vaults/details.dart';
+import 'package:aves/model/viewer/video_playback.dart';
+import 'package:aves/services/common/services.dart';
+import 'package:collection/collection.dart';
+import 'package:flutter/foundation.dart';
+import 'package:sqflite/sqflite.dart';
+
+class SqfliteLocalMediaDb implements LocalMediaDb {
+ late Database _db;
+
+ @override
+ Future<String> get path async => pContext.join(await getDatabasesPath(), 'metadata.db');
+
+ static const entryTable = SqfliteLocalMediaDbSchema.entryTable;
+ static const dateTakenTable = SqfliteLocalMediaDbSchema.dateTakenTable;
+ static const metadataTable = SqfliteLocalMediaDbSchema.metadataTable;
+ static const addressTable = SqfliteLocalMediaDbSchema.addressTable;
+ static const favouriteTable = SqfliteLocalMediaDbSchema.favouriteTable;
+ static const coverTable = SqfliteLocalMediaDbSchema.coverTable;
+ static const dynamicAlbumTable = SqfliteLocalMediaDbSchema.dynamicAlbumTable;
+ static const vaultTable = SqfliteLocalMediaDbSchema.vaultTable;
+ static const trashTable = SqfliteLocalMediaDbSchema.trashTable;
+ static const videoPlaybackTable = SqfliteLocalMediaDbSchema.videoPlaybackTable;
+
+ static const _entryInsertSliceMaxCount = 10000; // number of entries
+ static const _queryCursorBufferSize = 1000; // number of rows
+ static int _lastId = 0;
+
+ @override
+ int get nextId => ++_lastId;
+
+ @override
+ Future<void> init() async {
+ _db = await openDatabase(
+ await path,
+ onCreate: (db, version) => SqfliteLocalMediaDbSchema.createLatestVersion(db),
+ onUpgrade: LocalMediaDbUpgrader.upgradeDb,
+ version: 15,
+ );
+
+ final maxIdRows = await _db.rawQuery('SELECT MAX(id) AS maxId FROM $entryTable');
+ _lastId = (maxIdRows.firstOrNull?['maxId'] as int?) ?? 0;
+ }
+
+ @override
+ Future<int> dbFileSize() async {
+ final file = File(await path);
+ return await file.exists() ? await file.length() : 0;
+ }
+
+ @override
+ Future<void> reset() async {
+ debugPrint('$runtimeType reset');
+ await _db.close();
+ await deleteDatabase(await path);
+ await init();
+ }
+
+ @override
+ Future<void> removeIds(Set<int> ids, {Set<EntryDataType>? dataTypes}) async {
+ if (ids.isEmpty) return;
+
+ final _dataTypes = dataTypes ?? EntryDataType.values.toSet();
+
+ // using array in `whereArgs` and using it with `where arg IN ?` is a pain, so we prefer `batch` instead
+ final batch = _db.batch();
+ const where = 'id = ?';
+ const coverWhere = 'entryId = ?';
+ ids.forEach((id) {
+ final whereArgs = [id];
+ if (_dataTypes.contains(EntryDataType.basic)) {
+ batch.delete(entryTable, where: where, whereArgs: whereArgs);
+ }
+ if (_dataTypes.contains(EntryDataType.catalog)) {
+ batch.delete(dateTakenTable, where: where, whereArgs: whereArgs);
+ batch.delete(metadataTable, where: where, whereArgs: whereArgs);
+ }
+ if (_dataTypes.contains(EntryDataType.address)) {
+ batch.delete(addressTable, where: where, whereArgs: whereArgs);
+ }
+ if (_dataTypes.contains(EntryDataType.references)) {
+ batch.delete(favouriteTable, where: where, whereArgs: whereArgs);
+ batch.delete(coverTable, where: coverWhere, whereArgs: whereArgs);
+ batch.delete(trashTable, where: where, whereArgs: whereArgs);
+ batch.delete(videoPlaybackTable, where: where, whereArgs: whereArgs);
+ }
+ });
+ await batch.commit(noResult: true);
+ }
+
+ // entries
+
+ @override
+ Future<void> clearEntries() async {
+ final count = await _db.delete(entryTable, where: '1');
+ debugPrint('$runtimeType clearEntries deleted $count rows');
+ }
+
+ @override
+ Future<Set<AvesEntry>> loadEntries({int? origin, String? directory}) async {
+ String? where;
+ final whereArgs = <Object?>[];
+
+ if (origin != null) {
+ where = 'origin = ?';
+ whereArgs.add(origin);
+ }
+
+ final entries = <AvesEntry>{};
+ if (directory != null) {
+ final separator = pContext.separator;
+ if (!directory.endsWith(separator)) {
+ directory = '$directory$separator';
+ }
+
+ where = '${where != null ? '$where AND ' : ''}path LIKE ?';
+ whereArgs.add('$directory%');
+ final cursor = await _db.queryCursor(entryTable, where: where, whereArgs: whereArgs, bufferSize: _queryCursorBufferSize);
+
+ final dirLength = directory.length;
+ while (await cursor.moveNext()) {
+ final row = cursor.current;
+ // skip entries in subfolders
+ final path = row['path'] as String?;
+ if (path != null && !path.substring(dirLength).contains(separator)) {
+ entries.add(AvesEntry.fromMap(row));
+ }
+ }
+ } else {
+ final cursor = await _db.queryCursor(entryTable, where: where, whereArgs: whereArgs, bufferSize: _queryCursorBufferSize);
+ while (await cursor.moveNext()) {
+ entries.add(AvesEntry.fromMap(cursor.current));
+ }
+ }
+
+ return entries;
+ }
+
+ @override
+ Future<Set<AvesEntry>> loadEntriesById(Set<int> ids) => _getByIds(ids, entryTable, AvesEntry.fromMap);
+
+ @override
+ Future<void> insertEntries(Set<AvesEntry> entries) async {
+ if (entries.isEmpty) return;
+ final stopwatch = Stopwatch()..start();
+ // slice entries to avoid memory issues
+ int inserted = 0;
+ await Future.forEach(entries.slices(_entryInsertSliceMaxCount), (slice) async {
+ debugPrint('$runtimeType saveEntries inserting slice of [${inserted + 1}, ${inserted + slice.length}] entries');
+ final batch = _db.batch();
+ slice.forEach((entry) => _batchInsertEntry(batch, entry));
+ await batch.commit(noResult: true);
+ inserted += slice.length;
+ });
+ debugPrint('$runtimeType saveEntries complete in ${stopwatch.elapsed.inMilliseconds}ms for ${entries.length} entries');
+ }
+
+ @override
+ Future<void> updateEntry(int id, AvesEntry entry) async {
+ final batch = _db.batch();
+ batch.delete(entryTable, where: 'id = ?', whereArgs: [id]);
+ _batchInsertEntry(batch, entry);
+ await batch.commit(noResult: true);
+ }
+
+ void _batchInsertEntry(Batch batch, AvesEntry entry) {
+ batch.insert(
+ entryTable,
+ entry.toDatabaseMap(),
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ }
+
+ @override
+ Future<Set<AvesEntry>> searchLiveEntries(String query, {int? limit}) async {
+ final rows = await _db.query(
+ entryTable,
+ where: '(title LIKE ? OR path LIKE ?) AND trashed = ?',
+ whereArgs: ['%$query%', '%$query%', 0],
+ orderBy: 'sourceDateTakenMillis DESC',
+ limit: limit,
+ );
+ return rows.map(AvesEntry.fromMap).toSet();
+ }
+
+ @override
+ Future<Set<AvesEntry>> searchLiveDuplicates(int origin, Set<AvesEntry>? entries) async {
+ String where = 'origin = ? AND trashed = ?';
+ if (entries != null) {
+ where += ' AND contentId IN (${entries.map((v) => v.contentId).join(',')})';
+ }
+ final rows = await _db.rawQuery(
+ 'SELECT *, MAX(id) AS id'
+ ' FROM $entryTable'
+ ' WHERE $where'
+ ' GROUP BY contentId'
+ ' HAVING COUNT(id) > 1',
+ [origin, 0],
+ );
+ final duplicates = rows.map(AvesEntry.fromMap).toSet();
+ if (duplicates.isNotEmpty) {
+ debugPrint('$runtimeType found duplicates=$duplicates');
+ }
+ // returns most recent duplicate for each duplicated content ID
+ return duplicates;
+ }
+
+ // date taken
+
+ @override
+ Future<void> clearDates() async {
+ final count = await _db.delete(dateTakenTable, where: '1');
+ debugPrint('$runtimeType clearDates deleted $count rows');
+ }
+
+ @override
+ Future<Map<int?, int?>> loadDates() async {
+ final result = <int?, int?>{};
+ final cursor = await _db.queryCursor(dateTakenTable, bufferSize: _queryCursorBufferSize);
+ while (await cursor.moveNext()) {
+ final row = cursor.current;
+ result[row['id'] as int] = row['dateMillis'] as int? ?? 0;
+ }
+ return result;
+ }
+
+ // catalog metadata
+
+ @override
+ Future<void> clearCatalogMetadata() async {
+ final count = await _db.delete(metadataTable, where: '1');
+ debugPrint('$runtimeType clearMetadataEntries deleted $count rows');
+ }
+
+ @override
+ Future<Set<CatalogMetadata>> loadCatalogMetadata() async {
+ final result = <CatalogMetadata>{};
+ final cursor = await _db.queryCursor(metadataTable, bufferSize: _queryCursorBufferSize);
+ while (await cursor.moveNext()) {
+ result.add(CatalogMetadata.fromMap(cursor.current));
+ }
+ return result;
+ }
+
+ @override
+ Future<Set<CatalogMetadata>> loadCatalogMetadataById(Set<int> ids) => _getByIds(ids, metadataTable, CatalogMetadata.fromMap);
+
+ @override
+ Future<void> saveCatalogMetadata(Set<CatalogMetadata> metadataEntries) async {
+ if (metadataEntries.isEmpty) return;
+ final stopwatch = Stopwatch()..start();
+ try {
+ final batch = _db.batch();
+ metadataEntries.forEach((metadata) => _batchInsertMetadata(batch, metadata));
+ await batch.commit(noResult: true);
+ debugPrint('$runtimeType saveMetadata complete in ${stopwatch.elapsed.inMilliseconds}ms for ${metadataEntries.length} entries');
+ } catch (error, stack) {
+ debugPrint('$runtimeType failed to save metadata with error=$error\n$stack');
+ }
+ }
+
+ @override
+ Future<void> updateCatalogMetadata(int id, CatalogMetadata? metadata) async {
+ final batch = _db.batch();
+ batch.delete(dateTakenTable, where: 'id = ?', whereArgs: [id]);
+ batch.delete(metadataTable, where: 'id = ?', whereArgs: [id]);
+ _batchInsertMetadata(batch, metadata);
+ await batch.commit(noResult: true);
+ }
+
+ void _batchInsertMetadata(Batch batch, CatalogMetadata? metadata) {
+ if (metadata == null) return;
+ if (metadata.dateMillis != 0) {
+ batch.insert(
+ dateTakenTable,
+ {
+ 'id': metadata.id,
+ 'dateMillis': metadata.dateMillis,
+ },
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ }
+ batch.insert(
+ metadataTable,
+ metadata.toMap(),
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ }
+
+ // address
+
+ @override
+ Future<void> clearAddresses() async {
+ final count = await _db.delete(addressTable, where: '1');
+ debugPrint('$runtimeType clearAddresses deleted $count rows');
+ }
+
+ @override
+ Future<Set<AddressDetails>> loadAddresses() async {
+ final result = <AddressDetails>{};
+ final cursor = await _db.queryCursor(addressTable, bufferSize: _queryCursorBufferSize);
+ while (await cursor.moveNext()) {
+ result.add(AddressDetails.fromMap(cursor.current));
+ }
+ return result;
+ }
+
+ @override
+ Future<Set<AddressDetails>> loadAddressesById(Set<int> ids) => _getByIds(ids, addressTable, AddressDetails.fromMap);
+
+ @override
+ Future<void> saveAddresses(Set<AddressDetails> addresses) async {
+ if (addresses.isEmpty) return;
+ final stopwatch = Stopwatch()..start();
+ final batch = _db.batch();
+ addresses.forEach((address) => _batchInsertAddress(batch, address));
+ await batch.commit(noResult: true);
+ debugPrint('$runtimeType saveAddresses complete in ${stopwatch.elapsed.inMilliseconds}ms for ${addresses.length} entries');
+ }
+
+ @override
+ Future<void> updateAddress(int id, AddressDetails? address) async {
+ final batch = _db.batch();
+ batch.delete(addressTable, where: 'id = ?', whereArgs: [id]);
+ _batchInsertAddress(batch, address);
+ await batch.commit(noResult: true);
+ }
+
+ void _batchInsertAddress(Batch batch, AddressDetails? address) {
+ if (address == null) return;
+ batch.insert(
+ addressTable,
+ address.toMap(),
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ }
+
+ // vaults
+
+ @override
+ Future<void> clearVaults() async {
+ final count = await _db.delete(vaultTable, where: '1');
+ debugPrint('$runtimeType clearVaults deleted $count rows');
+ }
+
+ @override
+ Future<Set<VaultDetails>> loadAllVaults() async {
+ final result = <VaultDetails>{};
+ final cursor = await _db.queryCursor(vaultTable, bufferSize: _queryCursorBufferSize);
+ while (await cursor.moveNext()) {
+ result.add(VaultDetails.fromMap(cursor.current));
+ }
+ return result;
+ }
+
+ @override
+ Future<void> addVaults(Set<VaultDetails> rows) async {
+ if (rows.isEmpty) return;
+ final batch = _db.batch();
+ rows.forEach((row) => _batchInsertVault(batch, row));
+ await batch.commit(noResult: true);
+ }
+
+ @override
+ Future<void> updateVault(String oldName, VaultDetails row) async {
+ final batch = _db.batch();
+ batch.delete(vaultTable, where: 'name = ?', whereArgs: [oldName]);
+ _batchInsertVault(batch, row);
+ await batch.commit(noResult: true);
+ }
+
+ void _batchInsertVault(Batch batch, VaultDetails row) {
+ batch.insert(
+ vaultTable,
+ row.toMap(),
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ }
+
+ @override
+ Future<void> removeVaults(Set<VaultDetails> rows) async {
+ if (rows.isEmpty) return;
+
+ // using array in `whereArgs` and using it with `where arg IN ?` is a pain, so we prefer `batch` instead
+ final batch = _db.batch();
+ rows.map((v) => v.name).forEach((name) => batch.delete(vaultTable, where: 'name = ?', whereArgs: [name]));
+ await batch.commit(noResult: true);
+ }
+
+ // trash
+
+ @override
+ Future<void> clearTrashDetails() async {
+ final count = await _db.delete(trashTable, where: '1');
+ debugPrint('$runtimeType clearTrashDetails deleted $count rows');
+ }
+
+ @override
+ Future<Set<TrashDetails>> loadAllTrashDetails() async {
+ final result = <TrashDetails>{};
+ final cursor = await _db.queryCursor(trashTable, bufferSize: _queryCursorBufferSize);
+ while (await cursor.moveNext()) {
+ result.add(TrashDetails.fromMap(cursor.current));
+ }
+ return result;
+ }
+
+ @override
+ Future<void> updateTrash(int id, TrashDetails? details) async {
+ final batch = _db.batch();
+ batch.delete(trashTable, where: 'id = ?', whereArgs: [id]);
+ _batchInsertTrashDetails(batch, details);
+ await batch.commit(noResult: true);
+ }
+
+ void _batchInsertTrashDetails(Batch batch, TrashDetails? details) {
+ if (details == null) return;
+ batch.insert(
+ trashTable,
+ details.toMap(),
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ }
+
+ // favourites
+
+ @override
+ Future<void> clearFavourites() async {
+ final count = await _db.delete(favouriteTable, where: '1');
+ debugPrint('$runtimeType clearFavourites deleted $count rows');
+ }
+
+ @override
+ Future<Set<FavouriteRow>> loadAllFavourites() async {
+ final result = <FavouriteRow>{};
+ final cursor = await _db.queryCursor(favouriteTable, bufferSize: _queryCursorBufferSize);
+ while (await cursor.moveNext()) {
+ result.add(FavouriteRow.fromMap(cursor.current));
+ }
+ return result;
+ }
+
+ @override
+ Future<void> addFavourites(Set<FavouriteRow> rows) async {
+ if (rows.isEmpty) return;
+ final batch = _db.batch();
+ rows.forEach((row) => _batchInsertFavourite(batch, row));
+ await batch.commit(noResult: true);
+ }
+
+ @override
+ Future<void> updateFavouriteId(int id, FavouriteRow row) async {
+ final batch = _db.batch();
+ batch.delete(favouriteTable, where: 'id = ?', whereArgs: [id]);
+ _batchInsertFavourite(batch, row);
+ await batch.commit(noResult: true);
+ }
+
+ void _batchInsertFavourite(Batch batch, FavouriteRow row) {
+ batch.insert(
+ favouriteTable,
+ row.toMap(),
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ }
+
+ @override
+ Future<void> removeFavourites(Set<FavouriteRow> rows) async {
+ if (rows.isEmpty) return;
+ final ids = rows.map((row) => row.entryId);
+ if (ids.isEmpty) return;
+
+ // using array in `whereArgs` and using it with `where arg IN ?` is a pain, so we prefer `batch` instead
+ final batch = _db.batch();
+ ids.forEach((id) => batch.delete(favouriteTable, where: 'id = ?', whereArgs: [id]));
+ await batch.commit(noResult: true);
+ }
+
+ // covers
+
+ @override
+ Future<void> clearCovers() async {
+ final count = await _db.delete(coverTable, where: '1');
+ debugPrint('$runtimeType clearCovers deleted $count rows');
+ }
+
+ @override
+ Future<Set<CoverRow>> loadAllCovers() async {
+ final result = <CoverRow>{};
+ final cursor = await _db.queryCursor(coverTable, bufferSize: _queryCursorBufferSize);
+ while (await cursor.moveNext()) {
+ final rowMap = cursor.current;
+ final row = CoverRow.fromMap(rowMap);
+ if (row != null) {
+ result.add(row);
+ } else {
+ debugPrint('$runtimeType failed to deserialize cover from row=$rowMap');
+ }
+ }
+ return result;
+ }
+
+ @override
+ Future<void> addCovers(Set<CoverRow> rows) async {
+ if (rows.isEmpty) return;
+
+ final batch = _db.batch();
+ rows.forEach((row) => _batchInsertCover(batch, row));
+ await batch.commit(noResult: true);
+ }
+
+ @override
+ Future<void> updateCoverEntryId(int id, CoverRow row) async {
+ final batch = _db.batch();
+ batch.delete(coverTable, where: 'entryId = ?', whereArgs: [id]);
+ _batchInsertCover(batch, row);
+ await batch.commit(noResult: true);
+ }
+
+ void _batchInsertCover(Batch batch, CoverRow row) {
+ batch.insert(
+ coverTable,
+ row.toMap(),
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ }
+
+ @override
+ Future<void> removeCovers(Set<CollectionFilter> filters) async {
+ if (filters.isEmpty) return;
+
+ // for backward compatibility, remove stored JSON instead of removing de/reserialized filters
+ final obsoleteFilterJson = <String>{};
+
+ final rows = await _db.query(coverTable);
+ rows.forEach((row) {
+ final filterJson = row['filter'] as String?;
+ if (filterJson != null) {
+ final filter = CollectionFilter.fromJson(filterJson);
+ if (filters.any((v) => filter == v)) {
+ obsoleteFilterJson.add(filterJson);
+ }
+ }
+ });
+
+ // using array in `whereArgs` and using it with `where arg IN ?` is a pain, so we prefer `batch` instead
+ final batch = _db.batch();
+ obsoleteFilterJson.forEach((filterJson) => batch.delete(coverTable, where: 'filter = ?', whereArgs: [filterJson]));
+ await batch.commit(noResult: true);
+ }
+
+ // dynamic albums
+
+ @override
+ Future<int> clearDynamicAlbums() async {
+ final count = await _db.delete(dynamicAlbumTable, where: '1');
+ debugPrint('$runtimeType clearDynamicAlbums deleted $count rows');
+ return count;
+ }
+
+ @override
+ Future<Set<DynamicAlbumRow>> loadAllDynamicAlbums({int bufferSize = _queryCursorBufferSize}) async {
+ final result = <DynamicAlbumRow>{};
+ try {
+ final cursor = await _db.queryCursor(dynamicAlbumTable, bufferSize: bufferSize);
+ while (await cursor.moveNext()) {
+ final rowMap = cursor.current;
+ final row = DynamicAlbumRow.fromMap(rowMap);
+ if (row != null) {
+ result.add(row);
+ } else {
+ debugPrint('$runtimeType failed to deserialize dynamic album from row=$rowMap');
+ }
+ }
+ } catch (error, stack) {
+ debugPrint('$runtimeType failed to query table=$dynamicAlbumTable error=$error\n$stack');
+ if (bufferSize > 1) {
+ // a large row may prevent reading from the table because of cursor window size limit,
+ // so we retry without buffer to read as many rows as we can, and removing the others
+ debugPrint('$runtimeType retry to query table=$dynamicAlbumTable with no cursor buffer');
+ final safeRows = await loadAllDynamicAlbums(bufferSize: 1);
+ final clearedCount = await clearDynamicAlbums();
+ await addDynamicAlbums(safeRows);
+ final addedCount = safeRows.length;
+ final lostCount = clearedCount - addedCount;
+ debugPrint('$runtimeType kept $addedCount rows, lost $lostCount rows from table=$dynamicAlbumTable');
+ return safeRows;
+ }
+ }
+ return result;
+ }
+
+ @override
+ Future<void> addDynamicAlbums(Set<DynamicAlbumRow> rows) async {
+ if (rows.isEmpty) return;
+
+ final batch = _db.batch();
+ rows.forEach((row) => _batchInsertDynamicAlbum(batch, row));
+ await batch.commit(noResult: true);
+ }
+
+ void _batchInsertDynamicAlbum(Batch batch, DynamicAlbumRow row) {
+ batch.insert(
+ dynamicAlbumTable,
+ row.toMap(),
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ }
+
+ @override
+ Future<void> removeDynamicAlbums(Set<String> names) async {
+ if (names.isEmpty) return;
+
+ // using array in `whereArgs` and using it with `where arg IN ?` is a pain, so we prefer `batch` instead
+ final batch = _db.batch();
+ names.forEach((name) => batch.delete(dynamicAlbumTable, where: 'name = ?', whereArgs: [name]));
+ await batch.commit(noResult: true);
+ }
+
+ // video playback
+
+ @override
+ Future<void> clearVideoPlayback() async {
+ final count = await _db.delete(videoPlaybackTable, where: '1');
+ debugPrint('$runtimeType clearVideoPlayback deleted $count rows');
+ }
+
+ @override
+ Future<Set<VideoPlaybackRow>> loadAllVideoPlayback() async {
+ final result = <VideoPlaybackRow>{};
+ final cursor = await _db.queryCursor(videoPlaybackTable, bufferSize: _queryCursorBufferSize);
+ while (await cursor.moveNext()) {
+ final rowMap = cursor.current;
+ final row = VideoPlaybackRow.fromMap(rowMap);
+ if (row != null) {
+ result.add(row);
+ } else {
+ debugPrint('$runtimeType failed to deserialize video playback from row=$rowMap');
+ }
+ }
+ return result;
+ }
+
+ @override
+ Future<VideoPlaybackRow?> loadVideoPlayback(int id) async {
+ final rows = await _db.query(videoPlaybackTable, where: 'id = ?', whereArgs: [id]);
+ if (rows.isEmpty) return null;
+
+ return VideoPlaybackRow.fromMap(rows.first);
+ }
+
+ @override
+ Future<void> addVideoPlayback(Set<VideoPlaybackRow> rows) async {
+ if (rows.isEmpty) return;
+
+ final batch = _db.batch();
+ rows.forEach((row) => _batchInsertVideoPlayback(batch, row));
+ await batch.commit(noResult: true);
+ }
+
+ void _batchInsertVideoPlayback(Batch batch, VideoPlaybackRow row) {
+ batch.insert(
+ videoPlaybackTable,
+ row.toMap(),
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ }
+
+ @override
+ Future<void> removeVideoPlayback(Set<int> ids) async {
+ if (ids.isEmpty) return;
+
+ // using array in `whereArgs` and using it with `where arg IN ?` is a pain, so we prefer `batch` instead
+ final batch = _db.batch();
+ ids.forEach((id) => batch.delete(videoPlaybackTable, where: 'id = ?', whereArgs: [id]));
+ await batch.commit(noResult: true);
+ }
+
+ // convenience methods
+
+ Future<Set<T>> _getByIds<T>(Set<int> ids, String table, T Function(Map<String, Object?> row) mapRow) async {
+ final result = <T>{};
+ if (ids.isNotEmpty) {
+ final cursor = await _db.queryCursor(table, where: 'id IN (${ids.join(',')})', bufferSize: _queryCursorBufferSize);
+ while (await cursor.moveNext()) {
+ result.add(mapRow(cursor.current));
+ }
+ }
+ return result;
+ }
+}
diff --git a/lib/model/db/db_sqflite_schema.dart b/lib/model/db/db_sqflite_schema.dart
new file mode 100644
index 0000000..1d1d810
--- /dev/null
+++ b/lib/model/db/db_sqflite_schema.dart
@@ -0,0 +1,118 @@
+import 'package:sqflite/sqflite.dart';
+
+class SqfliteLocalMediaDbSchema {
+ static const entryTable = 'entry';
+ static const dateTakenTable = 'dateTaken';
+ static const metadataTable = 'metadata';
+ static const addressTable = 'address';
+ static const favouriteTable = 'favourites';
+ static const coverTable = 'covers';
+ static const dynamicAlbumTable = 'dynamicAlbums';
+ static const vaultTable = 'vaults';
+ static const trashTable = 'trash';
+ static const videoPlaybackTable = 'videoPlayback';
+
+ static const allTables = [
+ entryTable,
+ dateTakenTable,
+ metadataTable,
+ addressTable,
+ favouriteTable,
+ coverTable,
+ dynamicAlbumTable,
+ vaultTable,
+ trashTable,
+ videoPlaybackTable,
+ ];
+
+ static Future<void> createLatestVersion(Database db) async {
+ await Future.forEach(allTables, (table) => createTable(db, table));
+ }
+
+ static Future<void> createTable(Database db, String table) {
+ switch (table) {
+ case entryTable:
+ return db.execute('CREATE TABLE $entryTable('
+ 'id INTEGER PRIMARY KEY'
+ ', contentId INTEGER'
+ ', uri TEXT'
+ ', path TEXT'
+ ', sourceMimeType TEXT'
+ ', width INTEGER'
+ ', height INTEGER'
+ ', sourceRotationDegrees INTEGER'
+ ', sizeBytes INTEGER'
+ ', title TEXT'
+ ', dateAddedSecs INTEGER DEFAULT (strftime(\'%s\',\'now\'))'
+ ', dateModifiedMillis INTEGER'
+ ', sourceDateTakenMillis INTEGER'
+ ', durationMillis INTEGER'
+ ', trashed INTEGER DEFAULT 0'
+ ', origin INTEGER DEFAULT 0'
+ ')');
+ case dateTakenTable:
+ return db.execute('CREATE TABLE $dateTakenTable('
+ 'id INTEGER PRIMARY KEY'
+ ', dateMillis INTEGER'
+ ')');
+ case metadataTable:
+ return db.execute('CREATE TABLE $metadataTable('
+ 'id INTEGER PRIMARY KEY'
+ ', mimeType TEXT'
+ ', dateMillis INTEGER'
+ ', flags INTEGER'
+ ', rotationDegrees INTEGER'
+ ', xmpSubjects TEXT'
+ ', xmpTitle TEXT'
+ ', latitude REAL'
+ ', longitude REAL'
+ ', rating INTEGER'
+ ')');
+ case addressTable:
+ return db.execute('CREATE TABLE $addressTable('
+ 'id INTEGER PRIMARY KEY'
+ ', addressLine TEXT'
+ ', countryCode TEXT'
+ ', countryName TEXT'
+ ', adminArea TEXT'
+ ', locality TEXT'
+ ')');
+ case favouriteTable:
+ return db.execute('CREATE TABLE $favouriteTable('
+ 'id INTEGER PRIMARY KEY'
+ ')');
+ case coverTable:
+ return db.execute('CREATE TABLE $coverTable('
+ 'filter TEXT PRIMARY KEY'
+ ', entryId INTEGER'
+ ', packageName TEXT'
+ ', color TEXT'
+ ')');
+ case dynamicAlbumTable:
+ return db.execute('CREATE TABLE $dynamicAlbumTable('
+ 'name TEXT PRIMARY KEY'
+ ', filter TEXT'
+ ')');
+ case vaultTable:
+ return db.execute('CREATE TABLE $vaultTable('
+ 'name TEXT PRIMARY KEY'
+ ', autoLock INTEGER'
+ ', useBin INTEGER'
+ ', lockType TEXT'
+ ')');
+ case trashTable:
+ return db.execute('CREATE TABLE $trashTable('
+ 'id INTEGER PRIMARY KEY'
+ ', path TEXT'
+ ', dateMillis INTEGER'
+ ')');
+ case videoPlaybackTable:
+ return db.execute('CREATE TABLE $videoPlaybackTable('
+ 'id INTEGER PRIMARY KEY'
+ ', resumeTimeMillis INTEGER'
+ ')');
+ default:
+ throw Exception('unknown table=$table');
+ }
+ }
+}
diff --git a/lib/model/db/db_sqflite_upgrade.dart b/lib/model/db/db_sqflite_upgrade.dart
new file mode 100644
index 0000000..4796ea1
--- /dev/null
+++ b/lib/model/db/db_sqflite_upgrade.dart
@@ -0,0 +1,503 @@
+import 'dart:ui';
+
+import 'package:aves/model/covers.dart';
+import 'package:aves/model/db/db_extension.dart';
+import 'package:aves/model/db/db_sqflite_schema.dart';
+import 'package:aves/model/filters/filters.dart';
+import 'package:flutter/foundation.dart';
+import 'package:sqflite/sqflite.dart';
+
+class LocalMediaDbUpgrader {
+ static const entryTable = SqfliteLocalMediaDbSchema.entryTable;
+ static const dateTakenTable = SqfliteLocalMediaDbSchema.dateTakenTable;
+ static const metadataTable = SqfliteLocalMediaDbSchema.metadataTable;
+ static const addressTable = SqfliteLocalMediaDbSchema.addressTable;
+ static const favouriteTable = SqfliteLocalMediaDbSchema.favouriteTable;
+ static const coverTable = SqfliteLocalMediaDbSchema.coverTable;
+ static const dynamicAlbumTable = SqfliteLocalMediaDbSchema.dynamicAlbumTable;
+ static const vaultTable = SqfliteLocalMediaDbSchema.vaultTable;
+ static const trashTable = SqfliteLocalMediaDbSchema.trashTable;
+ static const videoPlaybackTable = SqfliteLocalMediaDbSchema.videoPlaybackTable;
+
+ // warning: "ALTER TABLE ... RENAME COLUMN ..." is not supported
+ // on SQLite <3.25.0, bundled on older Android devices
+ static Future<void> upgradeDb(Database db, int oldVersion, int newVersion) async {
+ debugPrint('DB will be upgraded from v$oldVersion to v$newVersion');
+ while (oldVersion < newVersion) {
+ switch (oldVersion) {
+ case 1:
+ await _upgradeFrom1(db);
+ case 2:
+ await _upgradeFrom2(db);
+ case 3:
+ await _upgradeFrom3(db);
+ case 4:
+ await _upgradeFrom4(db);
+ case 5:
+ await _upgradeFrom5(db);
+ case 6:
+ await _upgradeFrom6(db);
+ case 7:
+ await _upgradeFrom7(db);
+ case 8:
+ await _upgradeFrom8(db);
+ case 9:
+ await _upgradeFrom9(db);
+ case 10:
+ await _upgradeFrom10(db);
+ case 11:
+ await _upgradeFrom11(db);
+ case 12:
+ await _upgradeFrom12(db);
+ case 13:
+ await _upgradeFrom13(db);
+ case 14:
+ await _upgradeFrom14(db);
+ }
+ oldVersion++;
+ }
+ await _sanitize(db);
+ }
+
+ static Future<void> _sanitize(Database db) async {
+ // ensure all tables exist
+ await Future.forEach(SqfliteLocalMediaDbSchema.allTables, (table) async {
+ if (!(await db.tableExists(table))) {
+ await SqfliteLocalMediaDbSchema.createTable(db, table);
+ }
+ });
+
+ // remove rows referencing future entry IDs
+ final maxIdRows = await db.rawQuery('SELECT MAX(id) AS maxId FROM $entryTable');
+ final lastId = (maxIdRows.firstOrNull?['maxId'] as int?) ?? 0;
+ await db.delete(favouriteTable, where: 'id > ?', whereArgs: [lastId]);
+ await db.delete(coverTable, where: 'entryId > ?', whereArgs: [lastId]);
+ }
+
+ static Future<void> _upgradeFrom1(Database db) async {
+ debugPrint('upgrading DB from v1');
+
+ // rename column 'orientationDegrees' to 'sourceRotationDegrees'
+ const newEntryTable = '${entryTable}TEMP';
+ await db.execute('CREATE TABLE $newEntryTable ('
+ 'contentId INTEGER PRIMARY KEY'
+ ', uri TEXT'
+ ', path TEXT'
+ ', sourceMimeType TEXT'
+ ', width INTEGER'
+ ', height INTEGER'
+ ', sourceRotationDegrees INTEGER'
+ ', sizeBytes INTEGER'
+ ', title TEXT'
+ ', dateModifiedSecs INTEGER'
+ ', sourceDateTakenMillis INTEGER'
+ ', durationMillis INTEGER'
+ ')');
+ await db.rawInsert('INSERT INTO $newEntryTable (contentId,uri,path,sourceMimeType,width,height,sourceRotationDegrees,sizeBytes,title,dateModifiedSecs,sourceDateTakenMillis,durationMillis)'
+ ' SELECT contentId,uri,path,sourceMimeType,width,height,orientationDegrees,sizeBytes,title,dateModifiedSecs,sourceDateTakenMillis,durationMillis'
+ ' FROM $entryTable;');
+ await db.execute('DROP TABLE $entryTable;');
+ await db.execute('ALTER TABLE $newEntryTable RENAME TO $entryTable;');
+
+ // rename column 'videoRotation' to 'rotationDegrees'
+ const newMetadataTable = '${metadataTable}TEMP';
+ await db.execute('CREATE TABLE $newMetadataTable ('
+ 'contentId INTEGER PRIMARY KEY'
+ ', mimeType TEXT'
+ ', dateMillis INTEGER'
+ ', isAnimated INTEGER'
+ ', rotationDegrees INTEGER'
+ ', xmpSubjects TEXT'
+ ', xmpTitleDescription TEXT'
+ ', latitude REAL'
+ ', longitude REAL'
+ ')');
+ await db.rawInsert('INSERT INTO $newMetadataTable (contentId,mimeType,dateMillis,isAnimated,rotationDegrees,xmpSubjects,xmpTitleDescription,latitude,longitude)'
+ ' SELECT contentId,mimeType,dateMillis,isAnimated,videoRotation,xmpSubjects,xmpTitleDescription,latitude,longitude'
+ ' FROM $metadataTable;');
+ await db.rawInsert('UPDATE $newMetadataTable SET rotationDegrees = NULL WHERE rotationDegrees = 0;');
+ await db.execute('DROP TABLE $metadataTable;');
+ await db.execute('ALTER TABLE $newMetadataTable RENAME TO $metadataTable;');
+
+ // new column 'isFlipped'
+ await db.execute('ALTER TABLE $metadataTable ADD COLUMN isFlipped INTEGER;');
+ }
+
+ static Future<void> _upgradeFrom2(Database db) async {
+ debugPrint('upgrading DB from v2');
+
+ // merge columns 'isAnimated' and 'isFlipped' into 'flags'
+ const newMetadataTable = '${metadataTable}TEMP';
+ await db.execute('CREATE TABLE $newMetadataTable ('
+ 'contentId INTEGER PRIMARY KEY'
+ ', mimeType TEXT'
+ ', dateMillis INTEGER'
+ ', flags INTEGER'
+ ', rotationDegrees INTEGER'
+ ', xmpSubjects TEXT'
+ ', xmpTitleDescription TEXT'
+ ', latitude REAL'
+ ', longitude REAL'
+ ')');
+ await db.rawInsert('INSERT INTO $newMetadataTable (contentId,mimeType,dateMillis,flags,rotationDegrees,xmpSubjects,xmpTitleDescription,latitude,longitude)'
+ ' SELECT contentId,mimeType,dateMillis,ifnull(isAnimated,0)+ifnull(isFlipped,0)*2,rotationDegrees,xmpSubjects,xmpTitleDescription,latitude,longitude'
+ ' FROM $metadataTable;');
+ await db.execute('DROP TABLE $metadataTable;');
+ await db.execute('ALTER TABLE $newMetadataTable RENAME TO $metadataTable;');
+ }
+
+ static Future<void> _upgradeFrom3(Database db) async {
+ debugPrint('upgrading DB from v3');
+ await db.execute('CREATE TABLE $coverTable ('
+ 'filter TEXT PRIMARY KEY'
+ ', contentId INTEGER'
+ ')');
+ }
+
+ static Future<void> _upgradeFrom4(Database db) async {
+ debugPrint('upgrading DB from v4');
+ await db.execute('CREATE TABLE $videoPlaybackTable ('
+ 'contentId INTEGER PRIMARY KEY'
+ ', resumeTimeMillis INTEGER'
+ ')');
+ }
+
+ static Future<void> _upgradeFrom5(Database db) async {
+ debugPrint('upgrading DB from v5');
+ await db.execute('ALTER TABLE $metadataTable ADD COLUMN rating INTEGER;');
+ }
+
+ static Future<void> _upgradeFrom6(Database db) async {
+ debugPrint('upgrading DB from v6');
+ // new primary key column `id` instead of `contentId`
+ // new column `trashed`
+ await db.transaction((txn) async {
+ const newEntryTable = '${entryTable}TEMP';
+ await db.execute('CREATE TABLE $newEntryTable ('
+ 'id INTEGER PRIMARY KEY'
+ ', contentId INTEGER'
+ ', uri TEXT'
+ ', path TEXT'
+ ', sourceMimeType TEXT'
+ ', width INTEGER'
+ ', height INTEGER'
+ ', sourceRotationDegrees INTEGER'
+ ', sizeBytes INTEGER'
+ ', title TEXT'
+ ', dateModifiedSecs INTEGER'
+ ', sourceDateTakenMillis INTEGER'
+ ', durationMillis INTEGER'
+ ', trashed INTEGER DEFAULT 0'
+ ')');
+ await db.rawInsert('INSERT INTO $newEntryTable (id,contentId,uri,path,sourceMimeType,width,height,sourceRotationDegrees,sizeBytes,title,dateModifiedSecs,sourceDateTakenMillis,durationMillis)'
+ ' SELECT contentId,contentId,uri,path,sourceMimeType,width,height,sourceRotationDegrees,sizeBytes,title,dateModifiedSecs,sourceDateTakenMillis,durationMillis'
+ ' FROM $entryTable;');
+ await db.execute('DROP TABLE $entryTable;');
+ await db.execute('ALTER TABLE $newEntryTable RENAME TO $entryTable;');
+ });
+
+ // rename column `contentId` to `id`
+ await db.transaction((txn) async {
+ const newDateTakenTable = '${dateTakenTable}TEMP';
+ await db.execute('CREATE TABLE $newDateTakenTable ('
+ 'id INTEGER PRIMARY KEY'
+ ', dateMillis INTEGER'
+ ')');
+ await db.rawInsert('INSERT INTO $newDateTakenTable (id,dateMillis)'
+ ' SELECT contentId,dateMillis'
+ ' FROM $dateTakenTable;');
+ await db.execute('DROP TABLE $dateTakenTable;');
+ await db.execute('ALTER TABLE $newDateTakenTable RENAME TO $dateTakenTable;');
+ });
+
+ // rename column `contentId` to `id`
+ await db.transaction((txn) async {
+ const newMetadataTable = '${metadataTable}TEMP';
+ await db.execute('CREATE TABLE $newMetadataTable ('
+ 'id INTEGER PRIMARY KEY'
+ ', mimeType TEXT'
+ ', dateMillis INTEGER'
+ ', flags INTEGER'
+ ', rotationDegrees INTEGER'
+ ', xmpSubjects TEXT'
+ ', xmpTitleDescription TEXT'
+ ', latitude REAL'
+ ', longitude REAL'
+ ', rating INTEGER'
+ ')');
+ await db.rawInsert('INSERT INTO $newMetadataTable (id,mimeType,dateMillis,flags,rotationDegrees,xmpSubjects,xmpTitleDescription,latitude,longitude,rating)'
+ ' SELECT contentId,mimeType,dateMillis,flags,rotationDegrees,xmpSubjects,xmpTitleDescription,latitude,longitude,rating'
+ ' FROM $metadataTable;');
+ await db.execute('DROP TABLE $metadataTable;');
+ await db.execute('ALTER TABLE $newMetadataTable RENAME TO $metadataTable;');
+ });
+
+ // rename column `contentId` to `id`
+ await db.transaction((txn) async {
+ const newAddressTable = '${addressTable}TEMP';
+ await db.execute('CREATE TABLE $newAddressTable ('
+ 'id INTEGER PRIMARY KEY'
+ ', addressLine TEXT'
+ ', countryCode TEXT'
+ ', countryName TEXT'
+ ', adminArea TEXT'
+ ', locality TEXT'
+ ')');
+ await db.rawInsert('INSERT INTO $newAddressTable (id,addressLine,countryCode,countryName,adminArea,locality)'
+ ' SELECT contentId,addressLine,countryCode,countryName,adminArea,locality'
+ ' FROM $addressTable;');
+ await db.execute('DROP TABLE $addressTable;');
+ await db.execute('ALTER TABLE $newAddressTable RENAME TO $addressTable;');
+ });
+
+ // rename column `contentId` to `id`
+ await db.transaction((txn) async {
+ const newVideoPlaybackTable = '${videoPlaybackTable}TEMP';
+ await db.execute('CREATE TABLE $newVideoPlaybackTable ('
+ 'id INTEGER PRIMARY KEY'
+ ', resumeTimeMillis INTEGER'
+ ')');
+ await db.rawInsert('INSERT INTO $newVideoPlaybackTable (id,resumeTimeMillis)'
+ ' SELECT contentId,resumeTimeMillis'
+ ' FROM $videoPlaybackTable;');
+ await db.execute('DROP TABLE $videoPlaybackTable;');
+ await db.execute('ALTER TABLE $newVideoPlaybackTable RENAME TO $videoPlaybackTable;');
+ });
+
+ // rename column `contentId` to `id`
+ // remove column `path`
+ await db.transaction((txn) async {
+ const newFavouriteTable = '${favouriteTable}TEMP';
+ await db.execute('CREATE TABLE $newFavouriteTable ('
+ 'id INTEGER PRIMARY KEY'
+ ')');
+ await db.rawInsert('INSERT INTO $newFavouriteTable (id)'
+ ' SELECT contentId'
+ ' FROM $favouriteTable;');
+ await db.execute('DROP TABLE $favouriteTable;');
+ await db.execute('ALTER TABLE $newFavouriteTable RENAME TO $favouriteTable;');
+ });
+
+ // rename column `contentId` to `entryId`
+ await db.transaction((txn) async {
+ const newCoverTable = '${coverTable}TEMP';
+ await db.execute('CREATE TABLE $newCoverTable ('
+ 'filter TEXT PRIMARY KEY'
+ ', entryId INTEGER'
+ ')');
+ await db.rawInsert('INSERT INTO $newCoverTable (filter,entryId)'
+ ' SELECT filter,contentId'
+ ' FROM $coverTable;');
+ await db.execute('DROP TABLE $coverTable;');
+ await db.execute('ALTER TABLE $newCoverTable RENAME TO $coverTable;');
+ });
+
+ // new table
+ await db.execute('CREATE TABLE $trashTable ('
+ 'id INTEGER PRIMARY KEY'
+ ', path TEXT'
+ ', dateMillis INTEGER'
+ ')');
+ }
+
+ static Future<void> _upgradeFrom7(Database db) async {
+ debugPrint('upgrading DB from v7');
+ await db.execute('ALTER TABLE $coverTable ADD COLUMN packageName TEXT;');
+ await db.execute('ALTER TABLE $coverTable ADD COLUMN color INTEGER;');
+ }
+
+ static Future<void> _upgradeFrom8(Database db) async {
+ debugPrint('upgrading DB from v8');
+
+ // new column `dateAddedSecs`
+ await db.transaction((txn) async {
+ const newEntryTable = '${entryTable}TEMP';
+ await db.execute('CREATE TABLE $newEntryTable ('
+ 'id INTEGER PRIMARY KEY'
+ ', contentId INTEGER'
+ ', uri TEXT'
+ ', path TEXT'
+ ', sourceMimeType TEXT'
+ ', width INTEGER'
+ ', height INTEGER'
+ ', sourceRotationDegrees INTEGER'
+ ', sizeBytes INTEGER'
+ ', title TEXT'
+ ', dateAddedSecs INTEGER DEFAULT (strftime(\'%s\',\'now\'))'
+ ', dateModifiedSecs INTEGER'
+ ', sourceDateTakenMillis INTEGER'
+ ', durationMillis INTEGER'
+ ', trashed INTEGER DEFAULT 0'
+ ')');
+ await db.rawInsert('INSERT INTO $newEntryTable (id,contentId,uri,path,sourceMimeType,width,height,sourceRotationDegrees,sizeBytes,title,dateModifiedSecs,sourceDateTakenMillis,durationMillis,trashed)'
+ ' SELECT id,contentId,uri,path,sourceMimeType,width,height,sourceRotationDegrees,sizeBytes,title,dateModifiedSecs,sourceDateTakenMillis,durationMillis,trashed'
+ ' FROM $entryTable;');
+ await db.execute('DROP TABLE $entryTable;');
+ await db.execute('ALTER TABLE $newEntryTable RENAME TO $entryTable;');
+ });
+
+ // rename column `xmpTitleDescription` to `xmpTitle`
+ await db.transaction((txn) async {
+ const newMetadataTable = '${metadataTable}TEMP';
+ await db.execute('CREATE TABLE $newMetadataTable ('
+ 'id INTEGER PRIMARY KEY'
+ ', mimeType TEXT'
+ ', dateMillis INTEGER'
+ ', flags INTEGER'
+ ', rotationDegrees INTEGER'
+ ', xmpSubjects TEXT'
+ ', xmpTitle TEXT'
+ ', latitude REAL'
+ ', longitude REAL'
+ ', rating INTEGER'
+ ')');
+ await db.rawInsert('INSERT INTO $newMetadataTable (id,mimeType,dateMillis,flags,rotationDegrees,xmpSubjects,xmpTitle,latitude,longitude,rating)'
+ ' SELECT id,mimeType,dateMillis,flags,rotationDegrees,xmpSubjects,xmpTitleDescription,latitude,longitude,rating'
+ ' FROM $metadataTable;');
+ await db.execute('DROP TABLE $metadataTable;');
+ await db.execute('ALTER TABLE $newMetadataTable RENAME TO $metadataTable;');
+ });
+ }
+
+ static Future<void> _upgradeFrom9(Database db) async {
+ debugPrint('upgrading DB from v9');
+
+ // clean duplicates introduced before Aves v1.7.1
+ final duplicatedContentIdRows = await db.query(entryTable, columns: ['contentId'], groupBy: 'contentId', having: 'COUNT(id) > 1 AND contentId IS NOT NULL');
+ final duplicatedContentIds = duplicatedContentIdRows.map((row) => row['contentId'] as int?).nonNulls.toSet();
+ final duplicateIds = <int>{};
+ await Future.forEach(duplicatedContentIds, (contentId) async {
+ final rows = await db.query(entryTable, columns: ['id'], where: 'contentId = ?', whereArgs: [contentId]);
+ final ids = rows.map((row) => row['id'] as int?).nonNulls.toList()..sort();
+ if (ids.length > 1) {
+ ids.removeAt(0);
+ duplicateIds.addAll(ids);
+ }
+ });
+ final batch = db.batch();
+ const where = 'id = ?';
+ const coverWhere = 'entryId = ?';
+ duplicateIds.forEach((id) {
+ final whereArgs = [id];
+ batch.delete(entryTable, where: where, whereArgs: whereArgs);
+ batch.delete(dateTakenTable, where: where, whereArgs: whereArgs);
+ batch.delete(metadataTable, where: where, whereArgs: whereArgs);
+ batch.delete(addressTable, where: where, whereArgs: whereArgs);
+ batch.delete(favouriteTable, where: where, whereArgs: whereArgs);
+ batch.delete(coverTable, where: coverWhere, whereArgs: whereArgs);
+ batch.delete(trashTable, where: where, whereArgs: whereArgs);
+ batch.delete(videoPlaybackTable, where: where, whereArgs: whereArgs);
+ });
+ await batch.commit(noResult: true);
+ }
+
+ static Future<void> _upgradeFrom10(Database db) async {
+ debugPrint('upgrading DB from v10');
+
+ await db.execute('ALTER TABLE $entryTable ADD COLUMN origin INTEGER DEFAULT 0;');
+
+ await db.execute('CREATE TABLE $vaultTable ('
+ 'name TEXT PRIMARY KEY'
+ ', autoLock INTEGER'
+ ', useBin INTEGER'
+ ', lockType TEXT'
+ ')');
+ }
+
+ static Future<void> _upgradeFrom11(Database db) async {
+ debugPrint('upgrading DB from v11');
+
+ await db.execute('CREATE TABLE $dynamicAlbumTable ('
+ 'name TEXT PRIMARY KEY'
+ ', filter TEXT'
+ ')');
+ }
+
+ static Future<void> _upgradeFrom12(Database db) async {
+ debugPrint('upgrading DB from v12');
+
+ // retrieve covers stored with `int` color value
+ final rows = <CoverRow>{};
+ final cursor = await db.queryCursor(coverTable);
+ while (await cursor.moveNext()) {
+ final Map map = cursor.current;
+ final filter = CollectionFilter.fromJson(map['filter']);
+ if (filter != null) {
+ final colorValue = map['color'] as int?;
+ final color = colorValue != null ? Color(colorValue) : null;
+ final row = CoverRow(
+ filter: filter,
+ entryId: map['entryId'] as int?,
+ packageName: map['packageName'] as String?,
+ color: color,
+ );
+ rows.add(row);
+ }
+ }
+
+ // convert `color` column type from value number to JSON string
+ const newCoverTable = '${coverTable}TEMP';
+ await db.execute('CREATE TABLE $newCoverTable ('
+ 'filter TEXT PRIMARY KEY'
+ ', entryId INTEGER'
+ ', packageName TEXT'
+ ', color TEXT'
+ ')');
+
+ // insert covers with `string` color value
+ if (rows.isNotEmpty) {
+ final batch = db.batch();
+ rows.forEach((row) {
+ batch.insert(
+ newCoverTable,
+ row.toMap(),
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ });
+ await batch.commit(noResult: true);
+ }
+
+ await db.execute('DROP TABLE $coverTable;');
+ await db.execute('ALTER TABLE $newCoverTable RENAME TO $coverTable;');
+ }
+
+ static Future<void> _upgradeFrom13(Database db) async {
+ debugPrint('upgrading DB from v13');
+
+ if (await db.tableExists(entryTable)) {
+ // rename column 'dateModifiedSecs' to 'dateModifiedMillis'
+ const newEntryTable = '${entryTable}TEMP';
+ await db.execute('CREATE TABLE $newEntryTable ('
+ 'id INTEGER PRIMARY KEY'
+ ', contentId INTEGER'
+ ', uri TEXT'
+ ', path TEXT'
+ ', sourceMimeType TEXT'
+ ', width INTEGER'
+ ', height INTEGER'
+ ', sourceRotationDegrees INTEGER'
+ ', sizeBytes INTEGER'
+ ', title TEXT'
+ ', dateAddedSecs INTEGER DEFAULT (strftime(\'%s\',\'now\'))'
+ ', dateModifiedMillis INTEGER'
+ ', sourceDateTakenMillis INTEGER'
+ ', durationMillis INTEGER'
+ ', trashed INTEGER DEFAULT 0'
+ ', origin INTEGER DEFAULT 0'
+ ')');
+ await db.rawInsert('INSERT INTO $newEntryTable (id,contentId,uri,path,sourceMimeType,width,height,sourceRotationDegrees,sizeBytes,title,dateAddedSecs,dateModifiedMillis,sourceDateTakenMillis,durationMillis,trashed,origin)'
+ ' SELECT id,contentId,uri,path,sourceMimeType,width,height,sourceRotationDegrees,sizeBytes,title,dateAddedSecs,dateModifiedSecs*1000,sourceDateTakenMillis,durationMillis,trashed,origin'
+ ' FROM $entryTable;');
+ await db.execute('DROP TABLE $entryTable;');
+ await db.execute('ALTER TABLE $newEntryTable RENAME TO $entryTable;');
+ }
+ }
+
+ static Future<void> _upgradeFrom14(Database db) async {
+ debugPrint('upgrading DB from v14');
+
+ // transitional upgrade previously used to sanitize rebuildable tables
+ // (dateTakenTable, metadataTable, addressTable, trashTable, videoPlaybackTable)
+ // for users with a potentially corrupted DB following upgrade to v1.12.4
+ }
+}