DatabaseConnection.delayed constructor

DatabaseConnection.delayed(
  1. FutureOr<DatabaseConnection> connection,
  2. {SqlDialect dialect = SqlDialect.sqlite}
)

Database connection that is instantly available, but delegates work to a connection only available through a Future.

This can be useful in scenarios where you need to obtain a database instance synchronously, but need an async setup. A prime example here is DriftIsolate:

@DriftDatabase(...)
class MyDatabase extends _$MyDatabase {
  MyDatabase._connect(DatabaseConnection c): super.connect(c);

  factory MyDatabase.fromIsolate(DriftIsolate isolate) {
    return MyDatabase._connect(
      // isolate.connect() returns a future, but we can still return a
      // database synchronously thanks to DatabaseConnection.delayed!
      DatabaseConnection.delayed(isolate.connect()),
    );
  }
}

Implementation

factory DatabaseConnection.delayed(FutureOr<DatabaseConnection> connection,
    {SqlDialect dialect = SqlDialect.sqlite}) {
  if (connection is DatabaseConnection) {
    return connection;
  }

  return DatabaseConnection(
    LazyDatabase(() async => (await connection).executor, dialect: dialect),
    streamQueries: DelayedStreamQueryStore(
      connection.then((conn) => conn.streamQueries),
    ),
    connectionData: connection.then((c) => c.connectionData),
  );
}