acquireConnection method
Shares in-flight opens and rejects acquisitions for closing scopes.
Implementation
Future<ZenithDatabaseHandle> acquireConnection(
String tenantId, {
ZenithTenantScope? scope,
}) async {
if (_isDisposed) throw StateError('Database pool is disposed');
if (tenantId.isEmpty) throw ArgumentError.value(tenantId, 'tenantId');
if (scope != null) {
if (scope.id != tenantId) {
throw ArgumentError('Scope and tenant IDs differ');
}
if (scope.isDisposed || scope.isClosing) {
throw StateError('Scope is closing');
}
}
final releasing = _releasing[tenantId];
if (releasing != null) await releasing;
if (_isDisposed) throw StateError('Database pool is disposed');
if (scope != null && (scope.isDisposed || scope.isClosing)) {
throw StateError('Scope is closing');
}
final cached = _handles[tenantId];
final handle = cached != null && cached.isOpen
? cached
: await (_pending[tenantId] ?? _startOpen(tenantId));
if (_isDisposed ||
!handle.isOpen ||
!identical(_handles[tenantId], handle)) {
throw StateError('Connection ended before acquisition completed');
}
if (scope != null) {
if (scope.isDisposed || scope.isClosing) {
if (_owners[handle] == null || identical(_owners[handle], scope)) {
await _releaseOwned(tenantId, handle);
}
throw StateError('Scope ended while opening database');
}
bindScope(scope);
}
return handle;
}