Skip to main content

AsyncConnection

Struct AsyncConnection 

Source
pub struct AsyncConnection { /* private fields */ }
Expand description

An async connection to a Hyper database.

This is the async equivalent of Connection, designed for use in tokio-based async applications. All I/O operations are non-blocking.

§Example

use hyperdb_api::{AsyncConnection, CreateMode, Result};

#[tokio::main]
async fn main() -> Result<()> {
    let conn = AsyncConnection::connect(
        "localhost:7483",
        "example.hyper",
        CreateMode::CreateIfNotExists,
    ).await?;

    conn.execute_command("CREATE TABLE test (id INT)").await?;
    let count: i64 = conn.fetch_scalar("SELECT COUNT(*) FROM test").await?;

    conn.close().await?;
    Ok(())
}

Implementations§

Source§

impl AsyncConnection

Source

pub fn builder(endpoint: &str) -> AsyncConnectionBuilder

Returns a fluent AsyncConnectionBuilder pointed at endpoint.

Source

pub async fn connect( endpoint: &str, database: &str, mode: CreateMode, ) -> Result<Self>

Connects to a Hyper server (async).

Transport is auto-detected from the endpoint:

  • https:// or http:// → gRPC transport
  • Otherwise → TCP transport (PostgreSQL wire protocol)
§Errors
Source

pub async fn connect_with_auth( endpoint: &str, database: &str, mode: CreateMode, user: &str, password: &str, ) -> Result<Self>

Connects with authentication (async).

§Errors
Source

pub async fn without_database(endpoint: &str) -> Result<Self>

Connects to a server without attaching any database (async).

Useful for running CREATE DATABASE / DROP DATABASE without an active attachment.

§Errors

Returns Error::Io or Error::Client if the TCP handshake with endpoint fails.

Source

pub fn from_async_client(client: AsyncClient, database: Option<String>) -> Self

Builds an AsyncConnection from a pre-existing AsyncClient (TCP only).

Source

pub fn transport_type(&self) -> &'static str

Returns the transport type name (e.g., “TCP”, “gRPC”).

Source

pub fn supports_writes(&self) -> bool

Returns true if this connection supports write operations.

Source

pub fn database(&self) -> Option<&str>

Returns the database path.

Source

pub async fn execute_command(&self, sql: &str) -> Result<u64>

Executes a SQL command that doesn’t return rows (async).

Use for DDL statements (CREATE, DROP, ALTER) and DML statements (INSERT, UPDATE, DELETE). Returns the number of affected rows (DML) or 0 (DDL).

§Errors
  • Returns Error::Other on gRPC transports that do not yet support write operations.
  • Returns Error::Client if the SQL fails to parse or execute.
  • Returns Error::Io on transport-level I/O failures.
Source

pub async fn execute_batch(&self, statements: &[&str]) -> Result<u64>

Executes multiple SQL statements sequentially (async).

If any statement fails, execution stops and the error is returned wrapping the SQL preview for context.

§Errors

Returns an Error::Other wrapping the first failing statement’s error; the wrapping message includes the statement’s ordinal and an 80-character SQL preview.

Source

pub async fn execute_query(&self, query: &str) -> Result<AsyncRowset<'_>>

Executes a SQL query and returns a streaming AsyncRowset (async).

Results are streamed in chunks so memory usage stays constant regardless of result set size. See AsyncRowset for the row-level API and collectors.

§Errors
  • Returns Error::Client if the SQL is rejected by the server.
  • Returns Error::Io on transport-level I/O failures while opening the stream.
Source

pub async fn fetch_one<Q: AsRef<str>>(&self, query: Q) -> Result<Row>

Fetches a single row, erroring if the query returns zero rows.

§Errors
  • Returns the error from execute_query if the query fails.
  • Returns Error::Other with message "Query returned no rows" if the query produced zero rows.
Source

pub async fn fetch_optional<Q: AsRef<str>>( &self, query: Q, ) -> Result<Option<Row>>

Fetches a single row, returning None if the query is empty.

§Errors

Returns the error from execute_query if the query fails. An empty result set yields Ok(None), not an error.

Source

pub async fn fetch_all<Q: AsRef<str>>(&self, query: Q) -> Result<Vec<Row>>

Fetches all rows from a query.

§Errors

Returns the error from execute_query, or a transport error produced while draining every chunk.

Source

pub async fn fetch_one_as<T: FromRow>(&self, query: &str) -> Result<T>

Fetches a single row and maps it to a struct using crate::FromRow.

§Errors
Source

pub async fn fetch_all_as<T: FromRow>(&self, query: &str) -> Result<Vec<T>>

Fetches all rows and maps them to structs using crate::FromRow.

§Errors
Source

pub async fn fetch_scalar<T, Q>(&self, query: Q) -> Result<T>
where T: RowValue, Q: AsRef<str>,

Fetches a single non-NULL scalar value. Errors on empty / NULL.

§Errors
  • Returns the error from execute_query.
  • Returns Error::Other with message "Query returned no rows" if the query is empty.
  • Returns Error::Other with message "Scalar query returned NULL" if the first cell is SQL NULL.
Source

pub async fn fetch_optional_scalar<T, Q>(&self, query: Q) -> Result<Option<T>>
where T: RowValue, Q: AsRef<str>,

Fetches a single scalar value, allowing NULL (returns None).

§Errors

Returns the error from execute_query. An empty result still yields an error; SQL NULL in the first cell yields Ok(None).

Source

pub async fn query_count(&self, query: &str) -> Result<i64>

Returns the count from a SELECT COUNT(*) style query, defaulting to 0 on NULL.

§Errors

Returns the error from execute_query if the query itself fails.

Source

pub async fn execute_query_to_arrow(&self, sql: &str) -> Result<Bytes>

Executes a SELECT query and returns results as Arrow IPC stream bytes (async).

TCP uses COPY ... TO STDOUT WITH (FORMAT ARROWSTREAM); gRPC uses the native Arrow transport. Both return the same IPC stream shape.

§Errors

Propagates any Error::Client from the transport when the query fails or the server cannot produce Arrow IPC output.

Source

pub async fn export_table_to_arrow(&self, table_name: &str) -> Result<Bytes>

Exports an entire table to Arrow IPC stream format (async).

§Errors

See execute_query_to_arrow.

Source

pub async fn execute_query_to_batches( &self, sql: &str, ) -> Result<Vec<RecordBatch>>

Executes a SELECT query and returns parsed Arrow RecordBatches (async).

§Errors
  • Returns Error::Client if the query fails.
  • Returns Error::Other if the Arrow IPC payload cannot be decoded into record batches.
Source

pub async fn query_params( &self, query: &str, params: &[&dyn ToSqlParam], ) -> Result<AsyncRowset<'_>>

Executes a parameterized query with safely escaped parameters (async).

Mirrors the sync Connection::query_params; see that method for the design rationale around text-mode escaping vs. future native Bind/Execute support.

§Errors
  • Returns Error::Other on gRPC transports (prepared statements are TCP-only).
  • Returns Error::Client if the server rejects the statement at Parse, Bind, or Execute time.
  • Returns Error::Io on transport-level I/O failures.
Source

pub async fn command_params( &self, query: &str, params: &[&dyn ToSqlParam], ) -> Result<u64>

Executes a parameterized command (INSERT / UPDATE / DELETE) with binary-encoded parameters via Parse/Bind/Execute (async).

§Errors
  • Returns Error::Other on gRPC transports.
  • Returns Error::Client if the server rejects the statement at Parse, Bind, or Execute time.
  • Returns Error::Io on transport-level I/O failures.
Source

pub async fn create_database(&self, path: &str) -> Result<()>

Creates a new database file (async).

§Errors

Returns Error::Client if the server rejects CREATE DATABASE IF NOT EXISTS (e.g. the path is not writable).

Source

pub async fn drop_database(&self, path: &str) -> Result<()>

Drops (deletes) a database file (async).

§Errors

Returns Error::Client if the server rejects DROP DATABASE IF EXISTS (e.g. the database is still attached).

Source

pub async fn attach_database( &self, path: &str, alias: Option<&str>, ) -> Result<()>

Attaches a database file to the connection (async).

§Errors

Returns Error::Client if the server rejects the ATTACH DATABASE statement (file missing, permission denied, alias conflict).

Source

pub async fn detach_database(&self, alias: &str) -> Result<()>

Detaches a database alias from this connection (async).

§Errors

Returns Error::Client if the alias is not attached or the server cannot flush pending updates.

Source

pub async fn detach_all_databases(&self) -> Result<()>

Detaches all databases from this connection (async).

§Errors

Returns Error::Client if the server rejects DETACH ALL DATABASES.

Source

pub async fn copy_database(&self, source: &str, destination: &str) -> Result<()>

Copies a database file to a new path (async).

§Errors

Returns Error::Client if the server rejects the COPY DATABASE statement — e.g. the source is not attached or the destination path is not writable.

Source

pub async fn create_schema<T>(&self, schema_name: T) -> Result<()>
where T: TryInto<SchemaName>, Error: From<T::Error>,

Creates a schema in the database (async).

§Errors
  • Returns an error if schema_name cannot be converted to a SchemaName.
  • Returns Error::Client if the server rejects CREATE SCHEMA IF NOT EXISTS.
Source

pub async fn has_schema<T>(&self, schema: T) -> Result<bool>
where T: TryInto<SchemaName>, Error: From<T::Error>,

Checks whether a schema exists (async).

§Errors
  • Returns an error if schema cannot be converted to a SchemaName.
  • Returns Error::Client if the catalog lookup query fails.
Source

pub async fn has_table<T>(&self, table_name: T) -> Result<bool>
where T: TryInto<TableName>, Error: From<T::Error>,

Checks whether a table exists (async).

§Errors
  • Returns an error if table_name cannot be converted to a TableName.
  • Returns Error::Client if the catalog lookup query fails.
Source

pub async fn unload_database(&self) -> Result<()>

Unloads the database from memory but keeps the session alive (async).

§Errors

Returns Error::Client if the server rejects UNLOAD DATABASE (e.g. the database is in use by another session).

Source

pub async fn unload_release(&self) -> Result<()>

Releases the database completely from the session (async).

§Errors

Returns Error::Client if the server rejects UNLOAD RELEASE, most commonly because multiple databases are attached to the same session.

Source

pub async fn explain(&self, query: &str) -> Result<String>

Executes EXPLAIN and returns the plan text (async).

§Errors

Returns Error::Client if EXPLAIN <query> fails to parse or plan.

Source

pub async fn explain_analyze(&self, query: &str) -> Result<String>

Executes EXPLAIN ANALYZE and returns the plan with timing (async).

§Errors

Returns Error::Client if EXPLAIN ANALYZE <query> fails — this includes any runtime error raised by actually executing query.

Source

pub fn is_alive(&self) -> bool

Returns true if the connection is alive (passive check).

Source

pub async fn ping(&self) -> Result<()>

Actively pings the server with SELECT 1 (async).

§Errors

Returns Error::Client or Error::Io if the SELECT 1 round-trip fails — i.e. the connection is no longer usable.

Source

pub fn process_id(&self) -> i32

Returns the backend process ID, or 0 for gRPC transports.

Source

pub fn secret_key(&self) -> i32

Returns the secret key used for cancel requests, or 0 for gRPC.

Source

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

Returns a server parameter value by name (async).

Source

pub async fn server_version(&self) -> Option<ServerVersion>

Returns the server version as a parsed struct (async).

Source

pub fn set_notice_receiver( &mut self, receiver: Option<Box<dyn Fn(Notice) + Send + Sync>>, )

Sets the notice receiver callback for this connection.

Source

pub async fn cancel(&self) -> Result<()>

Cancels the currently running query (async).

§Errors
  • Returns Error::Other on gRPC transports — cancellation is not yet implemented for gRPC.
  • Returns Error::Client or Error::Io if the cancel-request connection to the server fails.
Source

pub async fn close(self) -> Result<()>

Closes the connection gracefully, detaching any attached database first (async).

§Errors
  • Returns Error::Other wrapping the transport close failure if the client cannot be shut down cleanly.
  • Returns Error::Other wrapping the detach failure if the attached database could not be detached but the transport close itself succeeded.
Source

pub fn async_tcp_client(&self) -> Option<&AsyncClient>

Returns a reference to the underlying async TCP client (None for gRPC).

Prefer the high-level AsyncConnection methods; this escape hatch remains for code that needs direct protocol access (e.g. custom COPY loops).

Source

pub async fn prepare(&self, query: &str) -> Result<AsyncPreparedStatement<'_>>

Prepares a SQL statement (async).

See Connection::prepare for semantics. The returned AsyncPreparedStatement can be executed many times with different parameter values.

§Errors

See prepare_typed — this method delegates to it with an empty OID list.

Source

pub async fn prepare_typed( &self, query: &str, param_types: &[Oid], ) -> Result<AsyncPreparedStatement<'_>>

Prepares a SQL statement with explicit parameter type OIDs (async).

§Errors
  • Returns Error::Other on gRPC transports (prepared statements are TCP-only).
  • Returns Error::Client if the server rejects the Parse message (SQL syntax error, unknown OID).
  • Returns Error::Io on transport-level I/O failures.
Source

pub async fn prepare_arc( self: &Arc<Self>, query: &str, ) -> Result<AsyncPreparedStatementOwned>

Owned-handle variant of prepare. Returns a 'static-lifetime AsyncPreparedStatementOwned that holds an Arc-cloned reference to self.

Intended for N-API consumers and any other caller that needs the prepared statement to outlive the stack frame where the connection is held.

§Errors

See prepare_typed_arc.

Source

pub async fn prepare_typed_arc( self: &Arc<Self>, query: &str, param_types: &[Oid], ) -> Result<AsyncPreparedStatementOwned>

Owned-handle variant of prepare_typed.

§Errors
Source

pub fn enable_query_stats(&self, provider: impl QueryStatsProvider + 'static)

Enables query statistics collection for this connection.

Source

pub fn disable_query_stats(&self)

Disables query statistics collection.

Source

pub fn last_query_stats(&self) -> Option<QueryStats>

Returns the stats for the most recent query (if enabled).

Source§

impl AsyncConnection

Source

pub async fn begin_transaction(&self) -> Result<()>

Begins an explicit transaction (async).

§Errors

Returns Error::Client if the server rejects BEGIN TRANSACTION (e.g. a transaction is already open on this session).

Source

pub async fn commit(&self) -> Result<()>

Commits the current transaction (async).

§Errors

Returns Error::Client if the server rejects COMMIT (e.g. no transaction is currently open).

Source

pub async fn rollback(&self) -> Result<()>

Rolls back the current transaction (async).

§Errors

Returns Error::Client if the server rejects ROLLBACK (e.g. no transaction is currently open).

Source

pub async fn transaction(&mut self) -> Result<AsyncTransaction<'_>>

Starts a transaction with an async RAII guard (async).

§Errors

Returns Error::Client if the internal BEGIN issued by AsyncTransaction::new fails.

Trait Implementations§

Source§

impl Debug for AsyncConnection

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

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