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
impl AsyncConnection
Sourcepub fn builder(endpoint: &str) -> AsyncConnectionBuilder
pub fn builder(endpoint: &str) -> AsyncConnectionBuilder
Returns a fluent AsyncConnectionBuilder
pointed at endpoint.
Sourcepub async fn connect(
endpoint: &str,
database: &str,
mode: CreateMode,
) -> Result<Self>
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://orhttp://→ gRPC transport- Otherwise → TCP transport (
PostgreSQLwire protocol)
§Errors
- Returns
Error::Io/Error::Clientif the handshake with the server fails. - Returns
Error::Clientif theCreateModeSQL (CREATE/DROP/ATTACH) is rejected by the server.
Sourcepub async fn connect_with_auth(
endpoint: &str,
database: &str,
mode: CreateMode,
user: &str,
password: &str,
) -> Result<Self>
pub async fn connect_with_auth( endpoint: &str, database: &str, mode: CreateMode, user: &str, password: &str, ) -> Result<Self>
Connects with authentication (async).
§Errors
- Returns
Error::Clientif authentication is rejected. - Returns
Error::Ioif the endpoint cannot be reached. - Returns
Error::Clientif theCreateModeSQL is rejected.
Sourcepub async fn without_database(endpoint: &str) -> Result<Self>
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.
Sourcepub fn from_async_client(client: AsyncClient, database: Option<String>) -> Self
pub fn from_async_client(client: AsyncClient, database: Option<String>) -> Self
Builds an AsyncConnection from a pre-existing AsyncClient (TCP only).
Sourcepub fn transport_type(&self) -> &'static str
pub fn transport_type(&self) -> &'static str
Returns the transport type name (e.g., “TCP”, “gRPC”).
Sourcepub fn supports_writes(&self) -> bool
pub fn supports_writes(&self) -> bool
Returns true if this connection supports write operations.
Sourcepub async fn execute_command(&self, sql: &str) -> Result<u64>
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::Otheron gRPC transports that do not yet support write operations. - Returns
Error::Clientif the SQL fails to parse or execute. - Returns
Error::Ioon transport-level I/O failures.
Sourcepub async fn execute_batch(&self, statements: &[&str]) -> Result<u64>
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.
Sourcepub async fn execute_query(&self, query: &str) -> Result<AsyncRowset<'_>>
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::Clientif the SQL is rejected by the server. - Returns
Error::Ioon transport-level I/O failures while opening the stream.
Sourcepub async fn fetch_one<Q: AsRef<str>>(&self, query: Q) -> Result<Row>
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_queryif the query fails. - Returns
Error::Otherwith message"Query returned no rows"if the query produced zero rows.
Sourcepub async fn fetch_optional<Q: AsRef<str>>(
&self,
query: Q,
) -> Result<Option<Row>>
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.
Sourcepub async fn fetch_all<Q: AsRef<str>>(&self, query: Q) -> Result<Vec<Row>>
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.
Sourcepub async fn fetch_one_as<T: FromRow>(&self, query: &str) -> Result<T>
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
- Returns the error from
fetch_one. - Returns whatever
FromRow::from_rowproduces when the row cannot be mapped.
Sourcepub async fn fetch_all_as<T: FromRow>(&self, query: &str) -> Result<Vec<T>>
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
- Returns the error from
fetch_all. - Returns the first error produced by
FromRow::from_rowon any row.
Sourcepub async fn fetch_scalar<T, Q>(&self, query: Q) -> Result<T>
pub async fn fetch_scalar<T, Q>(&self, query: Q) -> Result<T>
Fetches a single non-NULL scalar value. Errors on empty / NULL.
§Errors
- Returns the error from
execute_query. - Returns
Error::Otherwith message"Query returned no rows"if the query is empty. - Returns
Error::Otherwith message"Scalar query returned NULL"if the first cell is SQLNULL.
Sourcepub async fn fetch_optional_scalar<T, Q>(&self, query: Q) -> Result<Option<T>>
pub async fn fetch_optional_scalar<T, Q>(&self, query: Q) -> Result<Option<T>>
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).
Sourcepub async fn query_count(&self, query: &str) -> Result<i64>
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.
Sourcepub async fn execute_query_to_arrow(&self, sql: &str) -> Result<Bytes>
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.
Sourcepub async fn export_table_to_arrow(&self, table_name: &str) -> Result<Bytes>
pub async fn export_table_to_arrow(&self, table_name: &str) -> Result<Bytes>
Sourcepub async fn execute_query_to_batches(
&self,
sql: &str,
) -> Result<Vec<RecordBatch>>
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::Clientif the query fails. - Returns
Error::Otherif the Arrow IPC payload cannot be decoded into record batches.
Sourcepub async fn query_params(
&self,
query: &str,
params: &[&dyn ToSqlParam],
) -> Result<AsyncRowset<'_>>
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::Otheron gRPC transports (prepared statements are TCP-only). - Returns
Error::Clientif the server rejects the statement atParse,Bind, orExecutetime. - Returns
Error::Ioon transport-level I/O failures.
Sourcepub async fn command_params(
&self,
query: &str,
params: &[&dyn ToSqlParam],
) -> Result<u64>
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::Otheron gRPC transports. - Returns
Error::Clientif the server rejects the statement atParse,Bind, orExecutetime. - Returns
Error::Ioon transport-level I/O failures.
Sourcepub async fn create_database(&self, path: &str) -> Result<()>
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).
Sourcepub async fn drop_database(&self, path: &str) -> Result<()>
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).
Sourcepub async fn attach_database(
&self,
path: &str,
alias: Option<&str>,
) -> Result<()>
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).
Sourcepub async fn detach_database(&self, alias: &str) -> Result<()>
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.
Sourcepub async fn detach_all_databases(&self) -> Result<()>
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.
Sourcepub async fn copy_database(&self, source: &str, destination: &str) -> Result<()>
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.
Sourcepub async fn create_schema<T>(&self, schema_name: T) -> Result<()>
pub async fn create_schema<T>(&self, schema_name: T) -> Result<()>
Creates a schema in the database (async).
§Errors
- Returns an error if
schema_namecannot be converted to aSchemaName. - Returns
Error::Clientif the server rejectsCREATE SCHEMA IF NOT EXISTS.
Sourcepub async fn has_schema<T>(&self, schema: T) -> Result<bool>
pub async fn has_schema<T>(&self, schema: T) -> Result<bool>
Checks whether a schema exists (async).
§Errors
- Returns an error if
schemacannot be converted to aSchemaName. - Returns
Error::Clientif the catalog lookup query fails.
Sourcepub async fn has_table<T>(&self, table_name: T) -> Result<bool>
pub async fn has_table<T>(&self, table_name: T) -> Result<bool>
Checks whether a table exists (async).
§Errors
- Returns an error if
table_namecannot be converted to aTableName. - Returns
Error::Clientif the catalog lookup query fails.
Sourcepub async fn unload_database(&self) -> Result<()>
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).
Sourcepub async fn unload_release(&self) -> Result<()>
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.
Sourcepub async fn explain(&self, query: &str) -> Result<String>
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.
Sourcepub async fn explain_analyze(&self, query: &str) -> Result<String>
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.
Sourcepub async fn ping(&self) -> Result<()>
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.
Sourcepub fn process_id(&self) -> i32
pub fn process_id(&self) -> i32
Returns the backend process ID, or 0 for gRPC transports.
Sourcepub fn secret_key(&self) -> i32
pub fn secret_key(&self) -> i32
Returns the secret key used for cancel requests, or 0 for gRPC.
Sourcepub async fn parameter_status(&self, name: &str) -> Option<String>
pub async fn parameter_status(&self, name: &str) -> Option<String>
Returns a server parameter value by name (async).
Sourcepub async fn server_version(&self) -> Option<ServerVersion>
pub async fn server_version(&self) -> Option<ServerVersion>
Returns the server version as a parsed struct (async).
Sourcepub fn set_notice_receiver(
&mut self,
receiver: Option<Box<dyn Fn(Notice) + Send + Sync>>,
)
pub fn set_notice_receiver( &mut self, receiver: Option<Box<dyn Fn(Notice) + Send + Sync>>, )
Sets the notice receiver callback for this connection.
Sourcepub async fn cancel(&self) -> Result<()>
pub async fn cancel(&self) -> Result<()>
Cancels the currently running query (async).
§Errors
- Returns
Error::Otheron gRPC transports — cancellation is not yet implemented for gRPC. - Returns
Error::ClientorError::Ioif the cancel-request connection to the server fails.
Sourcepub async fn close(self) -> Result<()>
pub async fn close(self) -> Result<()>
Closes the connection gracefully, detaching any attached database first (async).
§Errors
- Returns
Error::Otherwrapping the transport close failure if the client cannot be shut down cleanly. - Returns
Error::Otherwrapping the detach failure if the attached database could not be detached but the transport close itself succeeded.
Sourcepub fn async_tcp_client(&self) -> Option<&AsyncClient>
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).
Sourcepub async fn prepare(&self, query: &str) -> Result<AsyncPreparedStatement<'_>>
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.
Sourcepub async fn prepare_typed(
&self,
query: &str,
param_types: &[Oid],
) -> Result<AsyncPreparedStatement<'_>>
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::Otheron gRPC transports (prepared statements are TCP-only). - Returns
Error::Clientif the server rejects theParsemessage (SQL syntax error, unknown OID). - Returns
Error::Ioon transport-level I/O failures.
Sourcepub async fn prepare_arc(
self: &Arc<Self>,
query: &str,
) -> Result<AsyncPreparedStatementOwned>
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.
Sourcepub async fn prepare_typed_arc(
self: &Arc<Self>,
query: &str,
param_types: &[Oid],
) -> Result<AsyncPreparedStatementOwned>
pub async fn prepare_typed_arc( self: &Arc<Self>, query: &str, param_types: &[Oid], ) -> Result<AsyncPreparedStatementOwned>
Owned-handle variant of prepare_typed.
§Errors
- Returns
Error::Otheron gRPC transports. - Returns
Error::Clientif the server rejects theParsemessage. - Returns
Error::Ioon transport-level I/O failures.
Sourcepub fn enable_query_stats(&self, provider: impl QueryStatsProvider + 'static)
pub fn enable_query_stats(&self, provider: impl QueryStatsProvider + 'static)
Enables query statistics collection for this connection.
Sourcepub fn disable_query_stats(&self)
pub fn disable_query_stats(&self)
Disables query statistics collection.
Sourcepub fn last_query_stats(&self) -> Option<QueryStats>
pub fn last_query_stats(&self) -> Option<QueryStats>
Returns the stats for the most recent query (if enabled).
Source§impl AsyncConnection
impl AsyncConnection
Sourcepub async fn begin_transaction(&self) -> Result<()>
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).
Sourcepub async fn commit(&self) -> Result<()>
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).
Sourcepub async fn rollback(&self) -> Result<()>
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).
Sourcepub async fn transaction(&mut self) -> Result<AsyncTransaction<'_>>
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§
Auto Trait Implementations§
impl !Freeze for AsyncConnection
impl !RefUnwindSafe for AsyncConnection
impl Send for AsyncConnection
impl Sync for AsyncConnection
impl Unpin for AsyncConnection
impl UnsafeUnpin for AsyncConnection
impl !UnwindSafe for AsyncConnection
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
Source§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request