From b6ec07d43fe9f0508ff809263dbae93dfc46809e Mon Sep 17 00:00:00 2001 From: Bagus <25834188+contactjavas@users.noreply.github.com> Date: Mon, 18 Sep 2023 18:41:18 +0700 Subject: [PATCH] drop corrupted db (PR by @turekj: https://github.com/Baseflow/flutter_cache_manager/pull/407) --- .../cache_object_provider.dart | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/flutter_cache_manager/lib/src/storage/cache_info_repositories/cache_object_provider.dart b/flutter_cache_manager/lib/src/storage/cache_info_repositories/cache_object_provider.dart index 16bf5656..8025a7a1 100644 --- a/flutter_cache_manager/lib/src/storage/cache_info_repositories/cache_object_provider.dart +++ b/flutter_cache_manager/lib/src/storage/cache_info_repositories/cache_object_provider.dart @@ -25,8 +25,12 @@ class CacheObjectProvider extends CacheInfoRepository if (!shouldOpenOnNewConnection()) { return openCompleter!.future; } + final path = await _getPath(); + await File(path).parent.create(recursive: true); + await _dropCorruptedDb(path); + db = await openDatabase(path, version: 3, onCreate: (Database db, int version) async { await db.execute(''' @@ -214,4 +218,41 @@ class CacheObjectProvider extends CacheInfoRepository } } } + + static Future _dropCorruptedDb(String path) async { + bool exists = false; + + try { + exists = await File(path).exists(); + } on FileSystemException { + // We can not read the file, so we assume it does not exist. + } catch (e) { + // We can not read the file, so we assume it does not exist. + } + + if (!exists) { + return; + } + + Database? pragmaDb; + bool isIntegral = true; + + try { + pragmaDb = await openDatabase(path); + final check = await pragmaDb.rawQuery("pragma integrity_check"); + isIntegral = check.length == 1 && check[0].values.first == "ok"; + } on DatabaseException { + isIntegral = false; + } catch (e) { + isIntegral = false; + } finally { + if (pragmaDb != null) { + await pragmaDb.close(); + } + } + + if (!isIntegral) { + await deleteDatabase(path); + } + } }