open method
Establishes a connection with a PostgreSQL database.
This method will return a Future that completes when the connection is established. Queries can be executed on this connection afterwards. If the connection fails to be established for any reason - including authentication - the returned Future will return with an error.
Connections may not be reopened after they are closed or opened more than once. If a connection has already been opened and this method is called, an exception will be thrown.
Implementation
Future open() async {
if (_hasConnectedPreviously) {
throw PostgreSQLException(
'Attempting to reopen a closed connection. Create a instance instead.');
}
try {
_hasConnectedPreviously = true;
if (isUnixSocket) {
_socket = await Socket.connect(
InternetAddress(host, type: InternetAddressType.unix), port)
.timeout(Duration(seconds: timeoutInSeconds));
} else {
_socket = await Socket.connect(host, port)
.timeout(Duration(seconds: timeoutInSeconds));
}
_observeDone(_socket!);
_framer = MessageFramer(encoding, timeZone, decodingSettings,
replicationMode != ReplicationMode.none);
// ignore: cancel_subscriptions
StreamSubscription<Uint8List>? plainSubscription;
final mode = effectiveSslMode;
if (mode != PgSslMode.disable) {
final negotiation = await _negotiateSsl(_socket!, mode,
timeout: timeoutInSeconds);
if (negotiation.secureSocket != null) {
_socket = negotiation.secureSocket;
_usingSsl = true;
} else {
// PgSslMode.prefer e o servidor não aceita SSL: segue sem SSL,
// reaproveitando a inscrição já feita no socket.
plainSubscription = negotiation.plainSubscription;
}
}
final connectionComplete = Completer();
if (plainSubscription != null) {
plainSubscription
..onData(_readData)
..onError(_close)
..onDone(_close);
} else {
_socket!.listen(_readData, onError: _close, onDone: _close);
}
_transitionToState(
_PostgreSQLConnectionStateSocketConnected(connectionComplete));
await connectionComplete.future
.timeout(Duration(seconds: timeoutInSeconds));
} on TimeoutException catch (e, st) {
final err = PostgreSQLException(
'Failed to connect to database $host:$port/$databaseName failed to connect.');
await _close(err, st);
rethrow;
} catch (e, st) {
await _close(e, st);
rethrow;
}
}