Skip to content

feat(database): Add database compression function#1027

Merged
GT-610 merged 3 commits intolollipopkit:mainfrom
GT-610:db/squash
Jan 26, 2026
Merged

feat(database): Add database compression function#1027
GT-610 merged 3 commits intolollipopkit:mainfrom
GT-610:db/squash

Conversation

@GT-610
Copy link
Copy Markdown
Collaborator

@GT-610 GT-610 commented Jan 26, 2026

Solve the database bloat issue by rebuilding connection_stats_enc.hive.

QQ_1769401645923

Resolve #924.

Summary by CodeRabbit

  • New Features

    • Added a database compaction tool in Connection Statistics with a confirmation dialog showing current size, progress indication, and success/error feedback; UI copy added for multiple locales.
  • Bug Fixes

    • Connection statistics are now cleared when deleting an individual server or deleting all servers.

✏️ Tip: You can customize this high-level summary in your review settings.

Add database compression functionality to the connection statistics page to reduce the size of the database file

Add multi-language support and related UI interactions
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jan 26, 2026

📝 Walkthrough

Walkthrough

Adds a database compaction operation to ConnectionStatsStore, exposes a UI flow to trigger compaction with size reporting, clears connection stats when servers are deleted, and adds localization strings for the compaction UI across multiple locales.

Changes

Cohort / File(s) Summary
Connection stats store
lib/data/store/connection_stats.dart
Added compact() to perform Hive box compaction with logging and error handling; tightened clearServerStats to delete keys equal to or prefixed by ${serverId}_.
Server provider cleanup
lib/data/provider/server/all.dart
After deleting a server or deleting all servers, invoke Stores.connectionStats.clearServerStats(id) or Stores.connectionStats.clearAll() to remove related connection stats.
Connection stats UI
lib/view/page/server/connection_stats.dart
Added dart:io import, _isCompacting state, app-bar compact IconButton, _showCompactDialog() flow to display current DB size, confirm compaction, run compaction, refresh size, and show success/error snackbars.
Localizations (added keys)
lib/l10n/app_en.arb, lib/l10n/app_de.arb, lib/l10n/app_es.arb, lib/l10n/app_fr.arb, lib/l10n/app_id.arb, lib/l10n/app_ja.arb, lib/l10n/app_nl.arb, lib/l10n/app_pt.arb, lib/l10n/app_ru.arb, lib/l10n/app_tr.arb, lib/l10n/app_uk.arb, lib/l10n/app_zh.arb, lib/l10n/app_zh_tw.arb
Added compactDatabase and compactDatabaseContent localization entries (some locales also add confirm) used by the new compaction dialog and UI.

Sequence Diagram

sequenceDiagram
    actor User
    participant UI as Connection Stats Page
    participant Store as ConnectionStatsStore
    participant Hive as Hive Box
    participant FS as File System

    User->>UI: Tap compact icon
    UI->>FS: Read DB file size (connection_stats_enc.hive)
    UI->>User: Show confirmation dialog with size
    User->>UI: Confirm
    UI->>UI: Close dialog, set _isCompacting = true
    UI->>Store: compact()
    Store->>Store: Log compaction start
    Store->>Hive: box.compact()
    Hive->>FS: Rebuild/optimize storage
    FS-->>Hive: Compaction done
    Hive-->>Store: Return success
    Store->>Store: Log compaction end
    Store-->>UI: return
    UI->>FS: Re-read DB file size
    UI->>UI: Clear _isCompacting, show snackbar with size delta
    UI-->>User: Display result
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly describes the main change: adding database compression functionality. It is specific, concise, and accurately reflects the primary purpose of the changeset.
Linked Issues check ✅ Passed The PR addresses the performance issue in #924 by implementing database compression for connection_stats_enc.hive to reduce startup time caused by database bloat.
Out of Scope Changes check ✅ Passed All changes are scoped to implementing database compression: backend store methods, UI dialog/button, localization strings, and connection statistics management. No unrelated modifications found.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 32c909d and 2977197.

📒 Files selected for processing (1)
  • lib/l10n/app_en.arb
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/l10n/app_en.arb

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🤖 Fix all issues with AI agents
In `@lib/data/provider/server/all.dart`:
- Around line 228-229: clearServerStats currently removes keys using
startsWith(serverId) which can delete unintended keys like "abc1"; update
Stores.connectionStats.clearServerStats to only match the serverId as a distinct
segment (for example require a delimiter such as `${serverId}_` or split the key
on '_' and compare the first segment exactly) so only keys belonging to that
server are cleared; locate the clearServerStats implementation and replace the
startsWith check with a delimiter-aware or segment comparison approach and
ensure callers (e.g., the deletion call in all.dart) keep using clearServerStats
unchanged.

In `@lib/l10n/app_de.arb`:
- Around line 49-50: The German locale is missing the l10n key "confirm" used by
the UI; add the key "confirm" with the appropriate German translation (e.g.,
"Bestätigen") to app_de.arb alongside the existing keys like "compactDatabase"
and "compactDatabaseContent" so the key name exactly matches the English source
(l10n.confirm) and keeps locales in sync for gen-l10n.

In `@lib/l10n/app_en.arb`:
- Around line 49-51: The string value for the localization key
"compactDatabaseContent" contains a typo ("shole") — update the value to replace
"shole" with "whole" so it reads "This will rebuild the whole database to reduce
file size." Ensure you only edit the value for "compactDatabaseContent"
(preserve the placeholder {size} and surrounding newlines) to avoid breaking
other keys.

In `@lib/l10n/app_nl.arb`:
- Line 50: The string value for the localization key "compactDatabaseContent"
contains a typo: change "Databasgrootte" to "Databasegrootte" so the Dutch reads
correctly; update the value associated with compactDatabaseContent to use
"Databasegrootte: {size}\n\nDit zal de hele database herbouwen om de
bestandsgrootte te verkleinen." ensuring only the typo is corrected and
escaping/newline formatting remains unchanged.

In `@lib/l10n/app_pt.arb`:
- Around line 49-50: You added the localization keys "compactDatabase" and
"compactDatabaseContent" in app_pt.arb but did not regenerate the Flutter
localization artifacts; run the localization generator by executing `flutter
gen-l10n` (or your project's configured l10n build command) to refresh generated
classes and arb translations, then include the updated generated files in the
commit so consumers of the new keys (e.g., the generated Localizations class and
lookup maps) are up to date.

In `@lib/l10n/app_ru.arb`:
- Around line 49-50: The Russian locale file is missing the "confirm" message
used by the UI (referenced as l10n.confirm in
lib/view/page/server/connection_stats.dart); add a "confirm" key and appropriate
Russian translation to lib/l10n/app_ru.arb (matching the base locale key name
"confirm") so gen-l10n sees the key in all locales and the code can access
l10n.confirm without errors.

In `@lib/view/page/server/connection_stats.dart`:
- Around line 222-231: The compaction call (Stores.connectionStats.compact())
can throw and currently skips resetting _isCompacting and surfacing errors; wrap
the await Stores.connectionStats.compact() and subsequent file-size logic in
try-catch-finally, catch exceptions and call context.showSnackBar(...) with the
error message (or libL10n failure text) to surface failures, and in finally
ensure if (mounted) setState(() => _isCompacting = false) so the spinner is
always cleared; keep existing context.pop() and mounted checks around UI updates
(sizeStr/newSizeStr) but move them into the try/finally blocks around the
compact call.
- Line 21: The compact button should be disabled while _isCompacting is true to
prevent concurrent dialog invocations: update the compact button's onPressed to
return null when _isCompacting is true (e.g., onPressed: _isCompacting ? null :
() => _startCompaction()), and ensure the compaction routine around the dialog
sets _isCompacting = true via setState before awaiting the async work/dialog and
sets _isCompacting = false in a finally block (also via setState) so the button
is re-enabled when done; refer to the _isCompacting field and the compact
button's onPressed handler to make these changes.
🧹 Nitpick comments (3)
lib/data/store/connection_stats.dart (1)

191-194: Add error handling around Hive compaction to surface failures.

box.compact() can throw HiveError during async writes (e.g., I/O failures or incorrect lifecycle state). Currently, failures will bubble uncaught. Wrap in try/catch to log the error and rethrow so the UI can report the failure gracefully.

♻️ Proposed refactor
  Future<void> compact() async {
    Loggers.app.info('Start compacting connection_stats database...');
-    await box.compact();
-    Loggers.app.info('Finished compacting connection_stats database');
+    try {
+      await box.compact();
+      Loggers.app.info('Finished compacting connection_stats database');
+    } catch (e, st) {
+      Loggers.app.warning('Failed compacting connection_stats database', e, st);
+      rethrow;
+    }
  }
lib/l10n/app_en.arb (1)

49-51: Regenerate localization after ARB updates.

Please run flutter gen-l10n to update generated localization files after these ARB changes. As per coding guidelines, ...

lib/view/page/server/connection_stats.dart (1)

210-237: Keep dialog actions in the extension for separation of concerns.

For consistency with the other dialog helpers, move _showCompactDialog into the existing extension below. Based on learnings, ...

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9ac8666 and 28844db.

⛔ Files ignored due to path filters (13)
  • lib/generated/l10n/l10n.dart is excluded by !**/generated/**
  • lib/generated/l10n/l10n_de.dart is excluded by !**/generated/**
  • lib/generated/l10n/l10n_en.dart is excluded by !**/generated/**
  • lib/generated/l10n/l10n_es.dart is excluded by !**/generated/**
  • lib/generated/l10n/l10n_fr.dart is excluded by !**/generated/**
  • lib/generated/l10n/l10n_id.dart is excluded by !**/generated/**
  • lib/generated/l10n/l10n_ja.dart is excluded by !**/generated/**
  • lib/generated/l10n/l10n_nl.dart is excluded by !**/generated/**
  • lib/generated/l10n/l10n_pt.dart is excluded by !**/generated/**
  • lib/generated/l10n/l10n_ru.dart is excluded by !**/generated/**
  • lib/generated/l10n/l10n_tr.dart is excluded by !**/generated/**
  • lib/generated/l10n/l10n_uk.dart is excluded by !**/generated/**
  • lib/generated/l10n/l10n_zh.dart is excluded by !**/generated/**
📒 Files selected for processing (16)
  • lib/data/provider/server/all.dart
  • lib/data/store/connection_stats.dart
  • lib/l10n/app_de.arb
  • lib/l10n/app_en.arb
  • lib/l10n/app_es.arb
  • lib/l10n/app_fr.arb
  • lib/l10n/app_id.arb
  • lib/l10n/app_ja.arb
  • lib/l10n/app_nl.arb
  • lib/l10n/app_pt.arb
  • lib/l10n/app_ru.arb
  • lib/l10n/app_tr.arb
  • lib/l10n/app_uk.arb
  • lib/l10n/app_zh.arb
  • lib/l10n/app_zh_tw.arb
  • lib/view/page/server/connection_stats.dart
🧰 Additional context used
📓 Path-based instructions (4)
lib/l10n/**/*.arb

📄 CodeRabbit inference engine (CLAUDE.md)

lib/l10n/**/*.arb: After modifying ARB files, run: flutter gen-l10n to regenerate localization
Keep localized strings in ARB files under lib/l10n/ (Flutter i18n)

Files:

  • lib/l10n/app_uk.arb
  • lib/l10n/app_zh.arb
  • lib/l10n/app_de.arb
  • lib/l10n/app_pt.arb
  • lib/l10n/app_fr.arb
  • lib/l10n/app_zh_tw.arb
  • lib/l10n/app_nl.arb
  • lib/l10n/app_ru.arb
  • lib/l10n/app_id.arb
  • lib/l10n/app_ja.arb
  • lib/l10n/app_tr.arb
  • lib/l10n/app_en.arb
  • lib/l10n/app_es.arb
lib/data/provider/**/*.dart

📄 CodeRabbit inference engine (CLAUDE.md)

Organize Riverpod providers by feature under lib/data/provider/

Files:

  • lib/data/provider/server/all.dart
lib/view/**/*.dart

📄 CodeRabbit inference engine (CLAUDE.md)

lib/view/**/*.dart: Prefer widgets/utilities from fl_lib for common UI (e.g., CustomAppBar, context.showRoundDialog, Input, Btnx.cancelOk)
Prefer using libL10n strings before adding new ones to project l10n
Split UI into build, actions, and utils; use extension on to separate concerns

Files:

  • lib/view/page/server/connection_stats.dart
lib/data/store/**/*.dart

📄 CodeRabbit inference engine (CLAUDE.md)

Persist state using Hive stores placed under lib/data/store/

Files:

  • lib/data/store/connection_stats.dart
🧠 Learnings (6)
📚 Learning: 2025-10-08T09:36:41.682Z
Learnt from: CR
Repo: lollipopkit/flutter_server_box PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-10-08T09:36:41.682Z
Learning: Applies to lib/l10n/**/*.arb : Keep localized strings in ARB files under lib/l10n/ (Flutter i18n)

Applied to files:

  • lib/l10n/app_uk.arb
  • lib/l10n/app_zh.arb
  • lib/l10n/app_pt.arb
  • lib/l10n/app_fr.arb
  • lib/l10n/app_ru.arb
  • lib/l10n/app_id.arb
  • lib/l10n/app_tr.arb
📚 Learning: 2025-10-08T09:36:41.682Z
Learnt from: CR
Repo: lollipopkit/flutter_server_box PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-10-08T09:36:41.682Z
Learning: Applies to lib/data/model/server/**/*.dart : Place server management models under lib/data/model/server/

Applied to files:

  • lib/data/provider/server/all.dart
📚 Learning: 2025-10-08T09:36:41.682Z
Learnt from: CR
Repo: lollipopkit/flutter_server_box PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-10-08T09:36:41.682Z
Learning: Applies to lib/view/**/*.dart : Prefer widgets/utilities from fl_lib for common UI (e.g., CustomAppBar, context.showRoundDialog, Input, Btnx.cancelOk)

Applied to files:

  • lib/view/page/server/connection_stats.dart
📚 Learning: 2025-10-08T09:36:41.682Z
Learnt from: CR
Repo: lollipopkit/flutter_server_box PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-10-08T09:36:41.682Z
Learning: Applies to lib/view/**/*.dart : Prefer using libL10n strings before adding new ones to project l10n

Applied to files:

  • lib/view/page/server/connection_stats.dart
📚 Learning: 2025-10-08T09:36:41.682Z
Learnt from: CR
Repo: lollipopkit/flutter_server_box PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-10-08T09:36:41.682Z
Learning: Applies to lib/view/**/*.dart : Split UI into build, actions, and utils; use extension on to separate concerns

Applied to files:

  • lib/view/page/server/connection_stats.dart
📚 Learning: 2025-10-08T09:36:41.682Z
Learnt from: CR
Repo: lollipopkit/flutter_server_box PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-10-08T09:36:41.682Z
Learning: Applies to lib/data/store/**/*.dart : Persist state using Hive stores placed under lib/data/store/

Applied to files:

  • lib/data/store/connection_stats.dart
🔇 Additional comments (10)
lib/l10n/app_tr.arb (1)

49-50: LGTM!

The Turkish localization entries for the database compaction feature are correctly added with proper placeholder usage ({size}). The translations align well with the feature's purpose.

As per coding guidelines, remember to run flutter gen-l10n to regenerate localization files after these changes.

lib/l10n/app_zh_tw.arb (1)

49-50: LGTM!

The Traditional Chinese localization entries are well-translated and consistent with the feature's purpose. The placeholder {size} is correctly preserved.

lib/l10n/app_ja.arb (1)

49-50: LGTM!

The Japanese localization entries are accurately translated and maintain proper placeholder usage for the database size parameter.

lib/l10n/app_fr.arb (1)

49-50: LGTM!

The French localization entries are well-translated with proper grammar and correct placeholder preservation.

lib/l10n/app_id.arb (1)

49-50: LGTM!

The Indonesian localization entries are correctly added with proper placeholder usage for the database compaction feature.

lib/l10n/app_zh.arb (1)

49-51: LGTM for the new localization entries.

Strings are consistent with the compaction flow and placeholders.

lib/l10n/app_uk.arb (1)

49-50: LGTM for the new localization entries.

lib/data/provider/server/all.dart (1)

249-249: Good cleanup of stats on bulk delete.

lib/l10n/app_es.arb (1)

49-50: LGTM for the new localization entries.

lib/view/page/server/connection_stats.dart (1)

1-1: LGTM — dart:io import is needed for file size checks.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

…ons and fix the statistics cleanup logic

Update the description of database compression operations in the multilingual files to explicitly state that data will not be lost

Fix the connection statistics cleanup logic to ensure correct matching of server IDs

Add error handling for the compression operation to prevent the UI from freezing
@GT-610
Copy link
Copy Markdown
Collaborator Author

GT-610 commented Jan 26, 2026

@coderabbitai _showCompactDialog needs to call setState() to manage the _isCompacting state, and as a static extension, it cannot access State instance members. Therefore, this method must be retained in the class body, consistent with _showClearAllDialog and _showClearServerStatsDialog (which are also in the class body).

So the last nitpick comments are not valid.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jan 26, 2026

Tip

For best results, initiate chat on the files or code changes.

@GT-610, you're absolutely right! Thank you for the clarification. Since _showCompactDialog needs to call setState() to manage the _isCompacting state and access instance members, it must remain in the class body. Static extension methods can't access instance state, so my previous suggestion to extract it was indeed not valid.

I appreciate you taking the time to explain the reasoning—keeping it consistent with _showClearAllDialog and _showClearServerStatsDialog makes perfect sense. 👍

@GT-610 GT-610 merged commit a0a62ac into lollipopkit:main Jan 26, 2026
3 checks passed
@GT-610 GT-610 deleted the db/squash branch January 26, 2026 05:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

redmi k40s手机使用本软件问题

1 participant