Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 18 additions & 6 deletions lib/core/storage/local_db.dart
Original file line number Diff line number Diff line change
Expand Up @@ -231,11 +231,14 @@ class LocalDb {
await db.delete('app_settings', where: 'key = ?', whereArgs: [key]);
}

final Map<String, int> _historyInsertCounts = {};

Future<void> recordSqlQueryHistory({
required int connectionId,
String? databaseName,
required String sqlText,
int maxEntries = kDefaultSqlHistoryCap,
bool forcePrune = false,
}) async {
final sql = sqlText.trim();
if (sql.isEmpty) return;
Expand All @@ -249,12 +252,21 @@ class LocalDb {
'sql_text': sql,
'recorded_at': now,
});
await _pruneSqlQueryHistoryBucket(
db,
connectionId: connectionId,
databaseName: dbKey,
maxEntries: maxEntries,
);

final bucketKey = '$connectionId::${dbKey ?? ''}';
final insertCount = (_historyInsertCounts[bucketKey] ?? 0) + 1;
_historyInsertCounts[bucketKey] = insertCount;

final batchThreshold = maxEntries <= 10 ? 1 : 10;
if (forcePrune || insertCount >= batchThreshold) {
_historyInsertCounts[bucketKey] = 0;
await _pruneSqlQueryHistoryBucket(
db,
connectionId: connectionId,
databaseName: dbKey,
maxEntries: maxEntries,
);
}
}

/// Keeps the newest [maxEntries] rows in a (connection, database) bucket.
Expand Down
30 changes: 30 additions & 0 deletions test/core/storage/sql_query_history_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,36 @@ void main() {
expect(list.map((e) => e.sqlText), ['q4', 'q3', 'q2']);
});

test('prunes in batches when maxEntries > 10', () async {
const row = ConnectionRow(
type: 'mysql',
name: 'M2',
host: '127.0.0.1',
port: 3306,
createdAt: '2026-01-01T00:00:00Z',
);
final id = await LocalDb.instance.addConnection(row);

// Insert 25 items with maxEntries = 15 (batch threshold = 10)
for (var i = 0; i < 25; i++) {
await LocalDb.instance.recordSqlQueryHistory(
connectionId: id,
databaseName: 'db_batch',
sqlText: 'query_$i',
maxEntries: 15,
);
}

final list = await LocalDb.instance.listSqlQueryHistory(
connectionId: id,
databaseName: 'db_batch',
limit: 100,
);
// On 20th insert (batch threshold 10 hit twice), pruned to 15. Then 5 more inserted (21..24) -> total 20 items.
expect(list.length, lessThanOrEqualTo(20));
expect(list.first.sqlText, 'query_24');
});

test('history lookup index includes database_name', () async {
await LocalDb.instance.getAppSetting('__touch__'); // ensure DB open
final dbFile = p.join(tempDir.path, 'querya_desktop', 'querya.db');
Expand Down
Loading