open method

Future open()

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));
    }

    _framer = MessageFramer(encoding);
    if (useSSL) {
      _socket =
          await _upgradeSocketToSSL(_socket!, timeout: timeoutInSeconds);
    }

    final connectionComplete = Completer();
    _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;
  }
}