connection method

Future<DatabaseDriver> connection([
  1. String? name
])

Returns the (lazily connected) driver for name or the default connection.

Implementation

Future<DatabaseDriver> connection([String? name]) {
  final connectionName = name ?? config.defaultConnection;
  final existing = _connections[connectionName];
  if (existing != null) {
    return Future<DatabaseDriver>.value(existing);
  }
  final pending = _connecting[connectionName];
  if (pending != null) {
    return pending;
  }
  // In a microtask, so that it is registered below before it can finish:
  // a factory that throws (a secret not there yet) ended it at once, its
  // `finally` removed nothing, and the failure stayed cached for good.
  final future = Future<DatabaseDriver>.microtask(() async {
    try {
      final driver = _createDriver(connectionName);
      await driver.connect();
      _connections[connectionName] = driver;
      _logger?.debug('Database connection [$connectionName] opened.');
      return driver;
    } finally {
      unawaited(_connecting.remove(connectionName));
    }
  });
  _connecting[connectionName] = future;
  return future;
}