Skip to main content

AsyncRawConnection

Struct AsyncRawConnection 

Source
pub struct AsyncRawConnection<S> { /* private fields */ }
Expand description

An async raw connection to a Hyper server.

This is the async equivalent of RawConnection, using tokio’s async I/O traits instead of std’s sync I/O.

The connection is generic over the stream type S, allowing it to work with different transport mechanisms (TcpStream, TlsStream, etc.) as long as they implement AsyncRead + AsyncWrite + Unpin.

Implementations§

Source§

impl<S> AsyncRawConnection<S>
where S: AsyncRead + AsyncWrite + Unpin,

Source

pub fn new(stream: S) -> Self

Creates a new async raw connection from a stream.

Initializes read and write buffers with default capacity (64 KB each). The connection is not yet authenticated - call startup() to begin the connection handshake.

Source

pub fn is_healthy(&self) -> bool

Returns true if this connection is still in a known-good state and safe to use for new requests. See super::connection::RawConnection::is_healthy for the full semantics — this is the async mirror with identical behavior.

Source

pub fn mark_desynchronized(&mut self)

Marks this connection as desynchronized.

Used by async result streams that are dropped mid-iteration: the Drop impl cannot await to drain trailing ErrorResponse + ReadyForQuery messages after sending a cancel, so it flags the connection so the next operation short-circuits with a clear error rather than hanging or misinterpreting stale server output.

Source

pub fn process_id(&self) -> i32

Returns the process ID assigned by the server.

Source

pub fn secret_key(&self) -> i32

Returns the secret key for cancel requests.

Source

pub fn stream(&self) -> &S

Returns a reference to the underlying stream.

Source

pub fn stream_mut(&mut self) -> &mut S

Returns a mutable reference to the underlying stream.

Source

pub fn parameter_status(&self, name: &str) -> Option<&str>

Returns a server parameter value by name.

Source

pub fn queue_copy_fail(&mut self, reason: &str)

Queues a CopyFail message in the write buffer (synchronous).

Called from AsyncCopyInWriter::Drop when a COPY session is abandoned without finish() or cancel(). The CopyFail is written to the buffer but NOT flushed (we can’t do async I/O from Drop). The next async operation will call drain_pending_copy_cancel to flush and drain the server’s ErrorResponse + ReadyForQuery before proceeding.

Source

pub async fn drain_pending_copy_cancel(&mut self) -> Result<()>

Drains a pending COPY cancel that was queued by queue_copy_fail().

If pending_copy_cancel is set, this flushes the CopyFail message to the server and reads messages until ReadyForQuery, restoring the connection to a usable state. Called automatically at the start of new operations (simple_query, query_binary, start_copy_in*).

§Errors

Returns Error (I/O) if flushing the queued CopyFail or reading the server’s drain responses fails. A successful drain clears pending_copy_cancel.

Source

pub async fn startup( &mut self, params: &[(&str, &str)], password: Option<&str>, ) -> Result<()>

Sends a startup message and performs initial handshake (async).

§Errors
  • Returns Error (auth) when the server requests an auth method and no password is supplied, when the offered SASL mechanisms exclude SCRAM-SHA-256, or when SCRAM state is missing at the SASL-continue / SASL-final step.
  • Returns Error (server) when the server sends an ErrorResponse during startup (unknown user, unknown database, etc.).
  • Returns Error (protocol) if a message arrives out of sequence.
  • Returns Error (I/O) on transport read/write failure.
Source

pub async fn simple_query(&mut self, query: &str) -> Result<Vec<Message>>

Sends a simple query and returns all messages until ReadyForQuery (async).

§Errors
  • Returns Error (connection) if the connection has been marked unhealthy.
  • Returns Error (server) when the server emits an ErrorResponse (SQL error, constraint violation, etc.).
  • Returns Error (I/O) / Error (closed) on transport read/write failure.
  • Propagates any error from Self::drain_pending_copy_cancel when a queued CopyFail needs to be flushed first.
Source

pub async fn query_binary(&mut self, query: &str) -> Result<Vec<Message>>

Sends a query using extended protocol with binary format results (async).

§Errors

Same failure modes as Self::simple_query.

Source

pub async fn start_query_binary(&mut self, query: &str) -> Result<()>

Starts a binary query but leaves result consumption to the caller (async).

§Errors
Source

pub async fn start_simple_query(&mut self, query: &str) -> Result<()>

Starts a simple query but leaves result consumption to the caller (async).

§Errors

Same failure modes as Self::start_query_binary.

Source

pub async fn start_execute_prepared( &mut self, statement_name: &str, params: &[Option<&[u8]>], column_count: usize, ) -> Result<()>

Starts an execute of a prepared statement but leaves result consumption to the caller (async).

Async mirror of super::connection::RawConnection::start_execute_prepared. See that method’s docs for the split format-code rationale (params use 1 = PG binary/BE, results use 2 = HyperBinary/LE).

§Errors
Source

pub async fn read_message(&mut self) -> Result<Message>

Reads a single message from the server (async).

§Errors
  • Returns Error (I/O) if reading from the transport fails or if Message::parse reports a malformed frame.
  • Returns Error (closed) when the transport reaches EOF (server closed the connection).
Source

pub async fn drain_until_ready(&mut self)

Async equivalent of super::connection::RawConnection::drain_until_ready. Unbounded; prefer drain_until_ready_bounded in destructors and other code paths where blocking indefinitely is unacceptable. Drain errors are logged via tracing::warn! and then swallowed.

Source

pub async fn drain_until_ready_bounded(&mut self, max_messages: usize) -> bool

Async equivalent of super::connection::RawConnection::drain_until_ready_bounded. See that function’s docs for the full semantics, including why we do not send a Sync before draining (it would produce an extra ReadyForQuery on the wire and corrupt the next query’s response).

Source

pub async fn consume_error(&mut self, body: &ErrorResponseBody) -> Error

Async equivalent of super::connection::RawConnection::consume_error. Parse the error body and drain the rest of the response in one call. Semantics are identical to the sync version, including the POST_ERROR_DRAIN_CAP safety valve — see that function’s docs for the rationale. Unbounded drain would be particularly dangerous here because a stalled read on the underlying async stream would hang the caller’s future indefinitely with no observable symptom; the bounded drain turns that into a loud tracing::warn! plus a connection marked for reconnect on next use.

Source

pub async fn flush(&mut self) -> Result<()>

Flushes the write buffer to the server (async).

§Errors

Returns Error (I/O) if writing the buffered bytes or flushing the underlying async transport fails.

Source

pub async fn terminate(&mut self) -> Result<()>

Sends a terminate message and closes the connection (async).

§Errors

Returns Error (I/O) if writing the Terminate frame or flushing the async transport fails.

Source

pub fn write_buf(&mut self) -> &mut BytesMut

Returns a mutable reference to the write buffer.

Source

pub async fn start_copy_in( &mut self, table_name: &str, columns: &[&str], ) -> Result<()>

Initiates a COPY IN operation with HyperBinary format (async).

§Errors

Same failure modes as Self::start_copy_in_with_format.

Source

pub async fn start_copy_in_with_format( &mut self, table_name: &str, columns: &[&str], format: &str, ) -> Result<()>

Initiates a COPY IN operation with a specified format (async).

§Errors
  • Returns Error (connection) if the connection has been marked unhealthy.
  • Returns Error (server) if the server rejects the generated COPY ... FROM STDIN statement.
  • Returns Error (I/O) on transport read/write failure.
  • Propagates any error from Self::drain_pending_copy_cancel.
Source

pub fn send_copy_data(&mut self, data: &[u8]) -> Result<()>

Sends COPY data to the server (sync - just buffers).

§Errors

Currently infallible — frame construction is pure. The Result return type is preserved for forward compatibility.

Source

pub async fn send_copy_data_direct(&mut self, data: &[u8]) -> Result<()>

Sends COPY data directly to the stream without internal buffering (async).

This writes the CopyData message directly to the TCP stream, letting the kernel’s TCP stack handle buffering. Use flush_stream() periodically to ensure data is sent.

§Errors
  • Returns Error (protocol) if data.len() + 4 exceeds u32::MAX (PostgreSQL’s per-message length cap).
  • Returns Error (I/O) if flushing buffered bytes or writing the header / payload to the async transport fails.
Source

pub async fn flush_stream(&mut self) -> Result<()>

Flushes the TCP stream without clearing the write buffer (async).

Use this with send_copy_data_direct() to periodically ensure data is sent to the server.

§Errors

Returns Error (I/O) if flushing the underlying async transport fails.

Source

pub async fn finish_copy(&mut self) -> Result<u64>

Finishes a COPY IN operation successfully (async).

§Errors
  • Returns Error (server) when the server emits an ErrorResponse during finalization (for example, a constraint violation from the accumulated rows).
  • Returns Error (I/O) / Error (closed) on transport read/write failure.
Source

pub async fn cancel_copy(&mut self, reason: &str) -> Result<()>

Cancels a COPY IN operation (async).

§Errors

Returns Error (I/O) if flushing the buffer or writing the CopyFail frame fails, or Error (closed) if the server drops the connection before returning ReadyForQuery.

Source

pub async fn copy_out(&mut self, query: &str) -> Result<Vec<u8>>

Executes a COPY … TO STDOUT query and returns all output data (async).

§Errors
  • Returns Error (connection) if the connection is unhealthy.
  • Returns Error (server) when the server rejects the COPY TO STDOUT statement via ErrorResponse.
  • Returns Error (I/O) / Error (closed) on transport read/write failure.
Source

pub async fn prepare( &mut self, name: &str, query: &str, param_types: &[Oid], ) -> Result<(Vec<Oid>, Vec<Column>)>

Prepares a statement using the extended query protocol (async).

§Errors
  • Returns Error (connection) if the connection is unhealthy.
  • Returns Error (server) if the server rejects the Parse request (SQL syntax error, unknown type OIDs, etc.).
  • Returns Error (I/O) on transport read/write failure.
Source

pub async fn execute_prepared( &mut self, statement_name: &str, params: &[Option<&[u8]>], column_count: usize, ) -> Result<Vec<Row>>

Executes a prepared statement with parameters (async).

§Errors
  • Returns Error (connection) if the connection is unhealthy.
  • Returns Error (server) if Bind / Execute fails on the server (parameter type mismatch, constraint violation, etc.).
  • Returns Error (I/O) / Error (closed) on transport read/write failure.
  • Propagates row-construction errors from super::row::Row::new if a DataRow cannot be decoded against the reported RowDescription.
Source

pub async fn execute_prepared_no_result( &mut self, statement_name: &str, params: &[Option<&[u8]>], ) -> Result<u64>

Executes a prepared statement that doesn’t return rows (async).

§Errors

Same failure modes as Self::execute_prepared (excluding row-construction errors — this path never builds rows).

Source

pub async fn close_statement(&mut self, statement_name: &str) -> Result<()>

Closes a prepared statement (async).

§Errors
  • Returns Error (connection) if the connection is unhealthy.
  • Returns Error (server) if the server reports an ErrorResponse during Close/Sync.
  • Returns Error (I/O) / Error (closed) on transport read/write failure.
  • Propagates any error from Self::drain_pending_copy_cancel.

Trait Implementations§

Source§

impl<S: Debug> Debug for AsyncRawConnection<S>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<S> Freeze for AsyncRawConnection<S>
where S: Freeze,

§

impl<S> RefUnwindSafe for AsyncRawConnection<S>
where S: RefUnwindSafe,

§

impl<S> Send for AsyncRawConnection<S>
where S: Send,

§

impl<S> Sync for AsyncRawConnection<S>
where S: Sync,

§

impl<S> Unpin for AsyncRawConnection<S>
where S: Unpin,

§

impl<S> UnsafeUnpin for AsyncRawConnection<S>
where S: UnsafeUnpin,

§

impl<S> UnwindSafe for AsyncRawConnection<S>
where S: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more