createBackgroundConnection static method

DatabaseConnection createBackgroundConnection(
  1. File file,
  2. {bool logStatements = false,
  3. DatabaseSetup? setup,
  4. IsolateSetup? isolateSetup,
  5. bool enableMigrations = true,
  6. bool cachePreparedStatements = _cacheStatementsByDefault}
)

Like createInBackground, except that it returns the whole DatabaseConnection instead of just the executor.

This creates a database writing data to the given file. The database runs in a background isolate and is stopped when closed.

Implementation

static DatabaseConnection createBackgroundConnection(
  File file, {
  bool logStatements = false,
  DatabaseSetup? setup,
  IsolateSetup? isolateSetup,
  bool enableMigrations = true,
  bool cachePreparedStatements = _cacheStatementsByDefault,
}) {
  return DatabaseConnection.delayed(Future.sync(() async {
    final receiveIsolate = ReceivePort();
    await Isolate.spawn(
      _NativeIsolateStartup.start,
      _NativeIsolateStartup(
        file.absolute.path,
        logStatements,
        cachePreparedStatements,
        enableMigrations,
        setup,
        isolateSetup,
        receiveIsolate.sendPort,
      ),
      debugName: 'Drift isolate worker for ${file.path}',
    );

    final driftIsolate = await receiveIsolate.first as DriftIsolate;
    receiveIsolate.close();

    return driftIsolate.connect(singleClientMode: true);
  }));
}