From 2d7318e29609acaeb236cf8097c8c17436a5a2d2 Mon Sep 17 00:00:00 2001 From: lifegpc Date: Mon, 27 May 2024 08:55:30 +0800 Subject: [PATCH] Add size property to database --- lib/platform/image_cache_io.dart | 34 ++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/lib/platform/image_cache_io.dart b/lib/platform/image_cache_io.dart index 95c299c..5a7d2c4 100644 --- a/lib/platform/image_cache_io.dart +++ b/lib/platform/image_cache_io.dart @@ -16,6 +16,7 @@ path TEXT, last_used INT, headers TEXT, realUrl TEXT, +size INT, PRIMARY KEY(url) );"""; const _allTables = ['images']; @@ -29,6 +30,7 @@ class ImageCaches { String? _exeDir; final Set _existingTable = {}; bool _inited = false; + static const version = 1; ImageCaches(); Future _desktopFilePath() async { final String? exe = await platformPath.getCurrentExe(); @@ -70,6 +72,30 @@ class ImageCaches { await _updateExistsTable(); final v = await _db!.getVersion(); _log.fine("Database version: $v"); + if (v < version) { + bool needOptimized = false; + if (v < 1 && _existingTable.contains("images")) { + await _db!.execute("ALTER TABLE images ADD size INT;"); + final re = await _db!.query("images", columns: ['url', 'path']); + for (final r in re) { + final f = _fs.file(r["path"] as String); + try { + final stats = await f.stat(); + Map map = {}; + map["size"] = stats.size; + await _db! + .update("images", map, where: 'url = ?', whereArgs: [r["url"]]); + } catch (e) { + _log.warning("Failed to stat ${f.path}: $e"); + await _db! + .delete("images", where: 'url = ?', whereArgs: [r["url"]]); + needOptimized = true; + } + } + } + await _db!.setVersion(version); + if (needOptimized) await _optimize(); + } if (_allTables.length != _existingTable.length || !_allTables.every((e) => _existingTable.contains(e))) { return false; @@ -93,6 +119,10 @@ class ImageCaches { } } + Future _optimize() async { + await _db!.execute("VACUUM;"); + } + Future init() async { sqfliteFfiInit(); _db = await databaseFactoryFfi.openDatabase(await _filePath); @@ -157,7 +187,7 @@ class ImageCaches { p = path.relative(p, from: _exeDir!); } await _db!.rawInsert( - "INSERT OR REPLACE INTO images VALUES (?, ?, ?, ?, ?);", - [uri, p, lastUsed, header, realUri]); + "INSERT OR REPLACE INTO images VALUES (?, ?, ?, ?, ?, ?);", + [uri, p, lastUsed, header, realUri, data.length]); } }