Skip to content

Commit f32b30c

Browse files
committed
Fix issue when calling connect() multiple times.
1 parent 58fa056 commit f32b30c

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

packages/powersync/lib/src/powersync_database.dart

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import 'dart:isolate';
33

44
import 'package:logging/logging.dart';
55
import 'package:powersync/src/log_internal.dart';
6+
import 'package:sqlite_async/mutex.dart';
67
import 'package:sqlite_async/sqlite3.dart' as sqlite;
78
import 'package:sqlite_async/sqlite_async.dart';
89

@@ -69,6 +70,9 @@ class PowerSyncDatabase with SqliteQueries implements SqliteConnection {
6970
/// null when disconnected, present when connecting or connected
7071
AbortController? _disconnecter;
7172

73+
/// Use to prevent multiple connections from being opened concurrently
74+
final Mutex _connectMutex = Mutex();
75+
7276
/// The Logger used by this [PowerSyncDatabase].
7377
///
7478
/// The default is [autoLogger], which logs to the console in debug builds.
@@ -190,6 +194,13 @@ class PowerSyncDatabase with SqliteQueries implements SqliteConnection {
190194
/// Throttle time between CRUD operations
191195
/// Defaults to 10 milliseconds.
192196
Duration crudThrottleTime = const Duration(milliseconds: 10)}) async {
197+
_connectMutex.lock(() =>
198+
_connect(connector: connector, crudThrottleTime: crudThrottleTime));
199+
}
200+
201+
Future<void> _connect(
202+
{required PowerSyncBackendConnector connector,
203+
required Duration crudThrottleTime}) async {
193204
await initialize();
194205

195206
// Disconnect if connected

packages/powersync/test/streaming_sync_test.dart

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,8 @@ void main() {
104104
});
105105

106106
test('multiple connect calls', () async {
107-
// Test repeatedly creating new PowerSync connections, then disconnect
108-
// and close the connection.
107+
// Test calling connect() multiple times.
108+
// We check that this does not cause multiple connections to be opened concurrently.
109109
final random = Random();
110110
var server = await createServer();
111111

0 commit comments

Comments
 (0)