openNativeConnection method

  1. @override
Database openNativeConnection(
  1. SqliteOpenOptions options
)

When opening the powersync connection and the standard write connection at the same time, one could fail with this error:

SqliteException(5): while opening the database, automatic extension loading failed: , database is locked (code 5)

It happens before we have a chance to set the busy timeout, so we just retry opening the database.

Usually a delay of 1-2ms is sufficient for the next try to succeed, but we increase the retry delay up to 16ms per retry, and a maximum of 500ms in total.

Implementation

@override
Database openNativeConnection(SqliteOpenOptions options) {
  enableExtension();

  final stopwatch = Stopwatch()..start();
  var retryDelay = 2;
  while (stopwatch.elapsedMilliseconds < 500) {
    try {
      return super.openNativeConnection(options);
    } catch (e) {
      if (e is SqliteException && e.resultCode == 5) {
        sleep(Duration(milliseconds: retryDelay));
        retryDelay = min(retryDelay * 2, 16);
        continue;
      }
      rethrow;
    }
  }
  throw AssertionError('Cannot reach this point');
}