getConnection method

Future<DatabaseConnection> getConnection()

Get a connection from the pool

Implementation

Future<DatabaseConnection> getConnection() async {
  if (_isClosed) {
    throw StateError('Connection pool is closed');
  }

  // Return available connection if exists
  if (_availableConnections.isNotEmpty) {
    final connection = _availableConnections.removeLast();
    _usedConnections.add(connection);
    return connection;
  }

  // Create new connection if under limit
  if (_usedConnections.length < maxConnections) {
    final connection = await DatabaseFactory.createConnection(config);
    _usedConnections.add(connection);
    return connection;
  }

  // Wait for a connection to become available
  throw StateError(
    'Connection pool exhausted. Max connections: $maxConnections',
  );
}