Skip to content

Commit 3966614

Browse files
committed
Close write connection after read connections.
1 parent f4c45fa commit 3966614

File tree

2 files changed

+57
-1
lines changed

2 files changed

+57
-1
lines changed

lib/src/connection_pool.dart

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,9 +174,12 @@ class SqliteConnectionPool with SqliteQueries implements SqliteConnection {
174174
@override
175175
Future<void> close() async {
176176
closed = true;
177-
await _writeConnection?.close();
178177
for (var connection in _readConnections) {
179178
await connection.close();
180179
}
180+
// Closing the write connection cleans up the journal files (-shm and -wal files).
181+
// It can only do that if there are no other open connections, so we close the
182+
// read-only connections first.
183+
await _writeConnection?.close();
181184
}
182185
}

test/close_test.dart

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import 'dart:io';
2+
3+
import 'package:sqlite_async/sqlite_async.dart';
4+
import 'package:test/test.dart';
5+
6+
import 'util.dart';
7+
8+
void main() {
9+
group('Close Tests', () {
10+
late String path;
11+
12+
setUp(() async {
13+
path = dbPath();
14+
await cleanDb(path: path);
15+
});
16+
17+
tearDown(() async {
18+
await cleanDb(path: path);
19+
});
20+
21+
createTables(SqliteDatabase db) async {
22+
await db.writeTransaction((tx) async {
23+
await tx.execute(
24+
'CREATE TABLE test_data(id INTEGER PRIMARY KEY AUTOINCREMENT, description TEXT)');
25+
});
26+
}
27+
28+
test('Open and close', () async {
29+
// Test that that the journal files are properly deleted after closing.
30+
// If the write connection is closed before the read connections, that is
31+
// not the case.
32+
33+
final db = await setupDatabase(path: path);
34+
await createTables(db);
35+
36+
await db.execute(
37+
'INSERT INTO test_data(description) VALUES(?)', ['Test Data']);
38+
await db.getAll('SELECT * FROM test_data');
39+
40+
expect(await File('$path-wal').exists(), equals(true));
41+
expect(await File('$path-shm').exists(), equals(true));
42+
43+
await db.close();
44+
45+
expect(await File(path).exists(), equals(true));
46+
47+
expect(await File('$path-wal').exists(), equals(false));
48+
expect(await File('$path-shm').exists(), equals(false));
49+
50+
expect(await File('$path-journal').exists(), equals(false));
51+
});
52+
});
53+
}

0 commit comments

Comments
 (0)