hyperdb_api/async_connection.rs
1// Copyright (c) 2026, Salesforce, Inc. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Async connection to Hyper database.
5//!
6//! This module provides [`AsyncConnection`] the async version of [`Connection`](crate::Connection).
7//! Use this when you're already in an async runtime (tokio).
8
9use std::any::Any;
10use std::sync::{Arc, Mutex};
11
12use crate::async_result::AsyncRowset;
13use crate::async_transport::{AsyncTcpTransport, AsyncTransport};
14use crate::error::{Error, Result};
15use crate::names::escape_sql_path;
16use crate::query_stats::{QueryStats, QueryStatsProvider};
17use crate::result::{Row, RowValue};
18use crate::CreateMode;
19
20/// An async connection to a Hyper database.
21///
22/// This is the async equivalent of [`Connection`](crate::Connection), designed for use
23/// in tokio-based async applications. All I/O operations are non-blocking.
24///
25/// # Example
26///
27/// ```no_run
28/// use hyperdb_api::{AsyncConnection, CreateMode, Result};
29///
30/// #[tokio::main]
31/// async fn main() -> Result<()> {
32/// let conn = AsyncConnection::connect(
33/// "localhost:7483",
34/// "example.hyper",
35/// CreateMode::CreateIfNotExists,
36/// ).await?;
37///
38/// conn.execute_command("CREATE TABLE test (id INT)").await?;
39/// let count: i64 = conn.fetch_scalar("SELECT COUNT(*) FROM test").await?;
40///
41/// conn.close().await?;
42/// Ok(())
43/// }
44/// ```
45pub struct AsyncConnection {
46 transport: AsyncTransport,
47 database: Option<String>,
48 stats_provider: Mutex<Option<Arc<dyn QueryStatsProvider>>>,
49 pending_stats: Mutex<Option<(Box<dyn Any + Send>, String)>>,
50}
51
52impl std::fmt::Debug for AsyncConnection {
53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 f.debug_struct("AsyncConnection")
55 .field("database", &self.database)
56 .finish_non_exhaustive()
57 }
58}
59
60impl AsyncConnection {
61 /// Returns a fluent [`AsyncConnectionBuilder`](crate::AsyncConnectionBuilder)
62 /// pointed at `endpoint`.
63 #[must_use]
64 pub fn builder(endpoint: &str) -> crate::AsyncConnectionBuilder {
65 crate::AsyncConnectionBuilder::new(endpoint)
66 }
67
68 /// Connects to a Hyper server (async).
69 ///
70 /// Transport is auto-detected from the endpoint:
71 /// - `https://` or `http://` → gRPC transport
72 /// - Otherwise → TCP transport (`PostgreSQL` wire protocol)
73 ///
74 /// # Errors
75 ///
76 /// - Returns [`Error::Io`] / [`Error::Connection`] if the handshake with
77 /// the server fails.
78 /// - Returns [`Error::Server`] if the `CreateMode` SQL (`CREATE`
79 /// / `DROP` / `ATTACH`) is rejected by the server.
80 pub async fn connect(endpoint: &str, database: &str, mode: CreateMode) -> Result<Self> {
81 let transport = AsyncTransport::connect(endpoint, Some(database)).await?;
82 let conn = AsyncConnection {
83 transport,
84 database: Some(database.to_string()),
85 stats_provider: Mutex::new(None),
86 pending_stats: Mutex::new(None),
87 };
88
89 if conn.transport.supports_writes() {
90 conn.handle_creation_mode(database, mode).await?;
91 conn.attach_and_set_path(database).await?;
92 }
93
94 Ok(conn)
95 }
96
97 /// Connects with authentication (async).
98 ///
99 /// # Errors
100 ///
101 /// - Returns [`Error::Authentication`] if authentication is rejected.
102 /// - Returns [`Error::Io`] if the endpoint cannot be reached.
103 /// - Returns [`Error::Server`] if the `CreateMode` SQL is rejected.
104 pub async fn connect_with_auth(
105 endpoint: &str,
106 database: &str,
107 mode: CreateMode,
108 user: &str,
109 password: &str,
110 ) -> Result<Self> {
111 let transport = AsyncTransport::connect_tcp_with_auth(endpoint, user, password).await?;
112 let conn = AsyncConnection {
113 transport,
114 database: Some(database.to_string()),
115 stats_provider: Mutex::new(None),
116 pending_stats: Mutex::new(None),
117 };
118
119 conn.handle_creation_mode(database, mode).await?;
120 conn.attach_and_set_path(database).await?;
121
122 Ok(conn)
123 }
124
125 /// Connects to a server without attaching any database (async).
126 ///
127 /// Useful for running `CREATE DATABASE` / `DROP DATABASE` without an
128 /// active attachment.
129 ///
130 /// # Errors
131 ///
132 /// Returns [`Error::Io`] or [`Error::Connection`] if the TCP handshake
133 /// with `endpoint` fails.
134 pub async fn without_database(endpoint: &str) -> Result<Self> {
135 let transport = AsyncTransport::connect_tcp(endpoint).await?;
136 Ok(AsyncConnection {
137 transport,
138 database: None,
139 stats_provider: Mutex::new(None),
140 pending_stats: Mutex::new(None),
141 })
142 }
143
144 /// Builds an `AsyncConnection` from a pre-existing `AsyncClient` (TCP only).
145 #[must_use]
146 pub fn from_async_client(
147 client: hyperdb_api_core::client::AsyncClient,
148 database: Option<String>,
149 ) -> Self {
150 AsyncConnection {
151 transport: AsyncTransport::Tcp(AsyncTcpTransport { client }),
152 database,
153 stats_provider: Mutex::new(None),
154 pending_stats: Mutex::new(None),
155 }
156 }
157
158 /// Builds an `AsyncConnection` from a pre-constructed transport.
159 ///
160 /// Used by [`AsyncConnectionBuilder`](crate::AsyncConnectionBuilder) to
161 /// stitch together a gRPC transport after its own config construction.
162 pub(crate) fn from_transport(transport: AsyncTransport, database: Option<String>) -> Self {
163 AsyncConnection {
164 transport,
165 database,
166 stats_provider: Mutex::new(None),
167 pending_stats: Mutex::new(None),
168 }
169 }
170
171 /// Runs the configured `CreateMode` as SQL (crate-public for use by
172 /// [`AsyncConnectionBuilder`](crate::AsyncConnectionBuilder)).
173 pub(crate) async fn handle_creation_mode_public(
174 &self,
175 database: &str,
176 mode: CreateMode,
177 ) -> Result<()> {
178 self.handle_creation_mode(database, mode).await
179 }
180
181 /// Attaches the database and sets `search_path` (crate-public for use
182 /// by [`AsyncConnectionBuilder`](crate::AsyncConnectionBuilder)).
183 pub(crate) async fn attach_and_set_path_public(&self, database: &str) -> Result<()> {
184 self.attach_and_set_path(database).await
185 }
186
187 async fn handle_creation_mode(&self, database: &str, mode: CreateMode) -> Result<()> {
188 let escaped_db = escape_sql_path(database);
189 match mode {
190 CreateMode::Create => {
191 self.execute_command(&format!("CREATE DATABASE {escaped_db}"))
192 .await?;
193 }
194 CreateMode::CreateIfNotExists => {
195 self.execute_command(&format!("CREATE DATABASE IF NOT EXISTS {escaped_db}"))
196 .await?;
197 }
198 CreateMode::CreateAndReplace => {
199 self.execute_command(&format!("DROP DATABASE IF EXISTS {escaped_db}"))
200 .await?;
201 self.execute_command(&format!("CREATE DATABASE {escaped_db}"))
202 .await?;
203 }
204 CreateMode::DoNotCreate => {}
205 }
206 Ok(())
207 }
208
209 async fn attach_and_set_path(&self, database: &str) -> Result<()> {
210 let escaped_db = escape_sql_path(database);
211 let db_alias = std::path::Path::new(database)
212 .file_stem()
213 .and_then(|s| s.to_str())
214 .unwrap_or("db");
215 let escaped_alias = escape_sql_path(db_alias);
216
217 self.execute_command(&format!("ATTACH DATABASE {escaped_db} AS {escaped_alias}"))
218 .await?;
219
220 self.execute_command(&format!("SET search_path TO {escaped_alias}, public"))
221 .await?;
222 Ok(())
223 }
224
225 /// Returns the transport type name (e.g., "TCP", "gRPC").
226 pub fn transport_type(&self) -> &'static str {
227 self.transport.transport_type().as_str()
228 }
229
230 /// Returns true if this connection supports write operations.
231 pub fn supports_writes(&self) -> bool {
232 self.transport.supports_writes()
233 }
234
235 /// Returns the database path.
236 pub fn database(&self) -> Option<&str> {
237 self.database.as_deref()
238 }
239
240 // =========================================================================
241 // Command Execution
242 // =========================================================================
243
244 /// Executes a SQL command that doesn't return rows (async).
245 ///
246 /// Use for DDL statements (CREATE, DROP, ALTER) and DML statements
247 /// (INSERT, UPDATE, DELETE). Returns the number of affected rows (DML)
248 /// or 0 (DDL).
249 ///
250 /// # Errors
251 ///
252 /// - Returns [`Error::FeatureNotSupported`] on gRPC transports that do not yet
253 /// support write operations.
254 /// - Returns [`Error::Server`] if the SQL fails to parse or execute.
255 /// - Returns [`Error::Io`] on transport-level I/O failures.
256 pub async fn execute_command(&self, sql: &str) -> Result<u64> {
257 let token = self.stats_before_query(sql);
258 let result = self.transport.execute_command(sql).await;
259 self.stats_store_pending(token, sql);
260 result
261 }
262
263 /// Executes multiple SQL statements sequentially (async).
264 ///
265 /// If any statement fails, execution stops and the error is returned
266 /// wrapping the SQL preview for context.
267 ///
268 /// # Errors
269 ///
270 /// Returns an [`Error::Internal`] wrapping the first failing statement's
271 /// error; the wrapping message includes the statement's ordinal and
272 /// an 80-character SQL preview.
273 pub async fn execute_batch(&self, statements: &[&str]) -> Result<u64> {
274 let mut total = 0u64;
275 for (i, stmt) in statements.iter().enumerate() {
276 if !stmt.trim().is_empty() {
277 total += self.execute_command(stmt).await.map_err(|e| {
278 let preview: String = stmt.chars().take(80).collect();
279 Error::internal(format!(
280 "execute_batch failed at statement {} of {}: {}: {}",
281 i + 1,
282 statements.len(),
283 preview,
284 e,
285 ))
286 })?;
287 }
288 }
289 Ok(total)
290 }
291
292 // =========================================================================
293 // Query Execution (Streaming)
294 // =========================================================================
295
296 /// Executes a SQL query and returns a streaming [`AsyncRowset`] (async).
297 ///
298 /// Results are streamed in chunks so memory usage stays constant
299 /// regardless of result set size. See [`AsyncRowset`] for the row-level
300 /// API and collectors.
301 ///
302 /// # Errors
303 ///
304 /// - Returns [`Error::Server`] if the SQL is rejected by the server.
305 /// - Returns [`Error::Io`] on transport-level I/O failures while
306 /// opening the stream.
307 pub async fn execute_query(&self, query: &str) -> Result<AsyncRowset<'_>> {
308 let token = self.stats_before_query(query);
309 let result = self.transport.execute_query_streaming(query).await;
310 self.stats_store_pending(token, query);
311 result
312 }
313
314 /// Fetches a single row, erroring if the query returns zero rows.
315 ///
316 /// # Errors
317 ///
318 /// - Returns the error from [`execute_query`](Self::execute_query) if
319 /// the query fails.
320 /// - Returns [`Error::Conversion`] with message `"Query returned no rows"` if
321 /// the query produced zero rows.
322 pub async fn fetch_one<Q: AsRef<str>>(&self, query: Q) -> Result<Row> {
323 self.execute_query(query.as_ref())
324 .await?
325 .require_first_row()
326 .await
327 }
328
329 /// Fetches a single row, returning `None` if the query is empty.
330 ///
331 /// # Errors
332 ///
333 /// Returns the error from [`execute_query`](Self::execute_query) if the
334 /// query fails. An empty result set yields `Ok(None)`, not an error.
335 pub async fn fetch_optional<Q: AsRef<str>>(&self, query: Q) -> Result<Option<Row>> {
336 self.execute_query(query.as_ref()).await?.first_row().await
337 }
338
339 /// Fetches all rows from a query.
340 ///
341 /// # Errors
342 ///
343 /// Returns the error from [`execute_query`](Self::execute_query), or a
344 /// transport error produced while draining every chunk.
345 pub async fn fetch_all<Q: AsRef<str>>(&self, query: Q) -> Result<Vec<Row>> {
346 self.execute_query(query.as_ref())
347 .await?
348 .collect_rows()
349 .await
350 }
351
352 /// Fetches a single row and maps it to a struct using [`crate::FromRow`].
353 ///
354 /// # Errors
355 ///
356 /// - Returns the error from [`fetch_one`](Self::fetch_one).
357 /// - Returns whatever [`FromRow::from_row`](crate::FromRow::from_row)
358 /// produces when the row cannot be mapped.
359 pub async fn fetch_one_as<T: crate::FromRow>(&self, query: &str) -> Result<T> {
360 let row = self.fetch_one(query).await?;
361 let indices = row
362 .schema()
363 .map(crate::row_accessor::RowAccessor::build_indices)
364 .unwrap_or_default();
365 T::from_row(crate::RowAccessor::new(&row, &indices))
366 }
367
368 /// Fetches all rows and maps them to structs using [`crate::FromRow`].
369 ///
370 /// # Errors
371 ///
372 /// - Returns the error from [`fetch_all`](Self::fetch_all).
373 /// - Returns the first error produced by
374 /// [`FromRow::from_row`](crate::FromRow::from_row) on any row.
375 pub async fn fetch_all_as<T: crate::FromRow>(&self, query: &str) -> Result<Vec<T>> {
376 let rows = self.fetch_all(query).await?;
377 // Build the column-name → index lookup once from the first
378 // row's schema; reuse for every row.
379 let indices = rows
380 .first()
381 .and_then(crate::result::Row::schema)
382 .map(crate::row_accessor::RowAccessor::build_indices)
383 .unwrap_or_default();
384 rows.iter()
385 .map(|r| T::from_row(crate::RowAccessor::new(r, &indices)))
386 .collect()
387 }
388
389 /// Returns a lazy `Stream` over rows, mapping each to `T` via
390 /// [`FromRow`].
391 ///
392 /// This is the streaming variant of [`fetch_all_as`](Self::fetch_all_as):
393 /// memory usage is bounded by the chunk size (default 64K rows), not by
394 /// the total row count. Use this for large result sets where collecting
395 /// all rows into a `Vec` would exceed memory limits.
396 ///
397 /// The column-name → index lookup table is built exactly once (on the
398 /// first non-empty chunk) and reused for all rows, so per-row mapping is
399 /// O(1) in column count.
400 ///
401 /// # Example
402 ///
403 /// ```no_run
404 /// # use hyperdb_api::{AsyncConnection, CreateMode, FromRow, RowAccessor, Result};
405 /// # use futures::StreamExt;
406 /// # struct User { id: i32, name: String }
407 /// # impl FromRow for User {
408 /// # fn from_row(row: RowAccessor<'_>) -> Result<Self> {
409 /// # Ok(User { id: row.get("id")?, name: row.get("name")? })
410 /// # }
411 /// # }
412 /// # async fn example(conn: &AsyncConnection) -> Result<()> {
413 /// let stream = conn.stream_as::<User>("SELECT id, name FROM users");
414 /// tokio::pin!(stream);
415 /// while let Some(row_result) = stream.next().await {
416 /// let user = row_result?;
417 /// println!("{}: {}", user.id, user.name);
418 /// }
419 /// # Ok(())
420 /// # }
421 /// ```
422 ///
423 /// # Errors
424 ///
425 /// Each yielded item is a `Result<T>`:
426 /// - The first item will be `Err(e)` if query submission fails (parse
427 /// failures, server errors, transport failures). The stream is lazy and
428 /// does not execute the query until first polled.
429 /// - Subsequent items are `Ok(T)` if the row was successfully mapped via
430 /// `FromRow`, or `Err(e)` if mapping failed (missing column, type
431 /// mismatch, NULL in a non-optional field). These errors surface lazily
432 /// during iteration.
433 ///
434 /// [`FromRow`]: crate::FromRow
435 pub fn stream_as<'a, T: crate::FromRow + 'a>(
436 &'a self,
437 query: &str,
438 ) -> impl futures_core::Stream<Item = Result<T>> + 'a {
439 // Own the query string so the stream doesn't borrow the &str arg
440 // across await points.
441 let query = query.to_owned();
442 async_stream::try_stream! {
443 let mut rs = self.execute_query(&query).await?; // submit err → first Err item
444 let mut indices: Option<std::collections::HashMap<String, usize>> = None;
445 while let Some(chunk) = rs.next_chunk().await? {
446 // Build the name→index map once, on the first chunk, after
447 // next_chunk() has materialized the schema (TCP sends the
448 // RowDescription as the first stream message). If the schema is
449 // somehow unavailable, fall back to an empty map so per-row
450 // lookups surface a `Missing` error — matching `fetch_all_as`'s
451 // `unwrap_or_default()` and the sync `stream_as`, rather than
452 // silently skipping the chunk.
453 if indices.is_none() {
454 let map = rs
455 .schema()
456 .map(|schema| crate::RowAccessor::build_owned_indices(&schema))
457 .unwrap_or_default();
458 indices = Some(map);
459 }
460 let idx = indices.get_or_insert_with(Default::default);
461 for row in &chunk {
462 yield T::from_row(crate::RowAccessor::new_owned(row, idx))?;
463 }
464 }
465 }
466 }
467
468 /// Fetches a single non-NULL scalar value. Errors on empty / NULL.
469 ///
470 /// # Errors
471 ///
472 /// - Returns the error from [`execute_query`](Self::execute_query).
473 /// - Returns [`Error::Conversion`] with message `"Query returned no rows"` if
474 /// the query is empty.
475 /// - Returns [`Error::Conversion`] with message `"Scalar query returned NULL"`
476 /// if the first cell is SQL `NULL`.
477 pub async fn fetch_scalar<T, Q>(&self, query: Q) -> Result<T>
478 where
479 T: RowValue,
480 Q: AsRef<str>,
481 {
482 self.execute_query(query.as_ref())
483 .await?
484 .require_scalar()
485 .await
486 }
487
488 /// Fetches a single scalar value, allowing NULL (returns `None`).
489 ///
490 /// # Errors
491 ///
492 /// Returns the error from [`execute_query`](Self::execute_query). An
493 /// empty result still yields an error; SQL `NULL` in the first cell
494 /// yields `Ok(None)`.
495 pub async fn fetch_optional_scalar<T, Q>(&self, query: Q) -> Result<Option<T>>
496 where
497 T: RowValue,
498 Q: AsRef<str>,
499 {
500 self.execute_query(query.as_ref()).await?.scalar().await
501 }
502
503 /// Returns the count from a `SELECT COUNT(*)` style query, defaulting
504 /// to 0 on NULL.
505 ///
506 /// # Errors
507 ///
508 /// Returns the error from [`execute_query`](Self::execute_query) if the
509 /// query itself fails.
510 pub async fn query_count(&self, query: &str) -> Result<i64> {
511 let opt: Option<i64> = self.fetch_optional_scalar(query).await?;
512 Ok(opt.unwrap_or(0))
513 }
514
515 // =========================================================================
516 // Arrow Queries
517 // =========================================================================
518
519 /// Executes a SELECT query and returns results as Arrow IPC stream bytes (async).
520 ///
521 /// TCP uses `COPY ... TO STDOUT WITH (FORMAT ARROWSTREAM)`; gRPC uses
522 /// the native Arrow transport. Both return the same IPC stream shape.
523 ///
524 /// # Errors
525 ///
526 /// Propagates any [`Error::Server`] from the transport when the query
527 /// fails or the server cannot produce Arrow IPC output.
528 pub async fn execute_query_to_arrow(&self, sql: &str) -> Result<bytes::Bytes> {
529 self.transport.execute_query_to_arrow(sql).await
530 }
531
532 /// Exports an entire table to Arrow IPC stream format (async).
533 ///
534 /// # Errors
535 ///
536 /// See [`execute_query_to_arrow`](Self::execute_query_to_arrow).
537 pub async fn export_table_to_arrow(&self, table_name: &str) -> Result<bytes::Bytes> {
538 self.execute_query_to_arrow(&format!("SELECT * FROM {table_name}"))
539 .await
540 }
541
542 /// Executes a SELECT query and returns parsed Arrow `RecordBatch`es (async).
543 ///
544 /// # Errors
545 ///
546 /// - Returns [`Error::Server`] if the query fails.
547 /// - Returns [`Error::Conversion`] if the Arrow IPC payload cannot be
548 /// decoded into record batches.
549 pub async fn execute_query_to_batches(
550 &self,
551 sql: &str,
552 ) -> Result<Vec<arrow::record_batch::RecordBatch>> {
553 let arrow_data = self.execute_query_to_arrow(sql).await?;
554 crate::arrow_result::parse_arrow_ipc(arrow_data)
555 }
556
557 // =========================================================================
558 // Parameterized Queries
559 // =========================================================================
560
561 /// Executes a parameterized query with safely escaped parameters (async).
562 ///
563 /// Mirrors the sync [`Connection::query_params`](crate::Connection::query_params);
564 /// see that method for the design rationale around text-mode escaping
565 /// vs. future native Bind/Execute support.
566 ///
567 /// # Errors
568 ///
569 /// - Returns [`Error::FeatureNotSupported`] on gRPC transports (prepared statements
570 /// are TCP-only).
571 /// - Returns [`Error::Server`] if the server rejects the statement at
572 /// `Parse`, `Bind`, or `Execute` time.
573 /// - Returns [`Error::Io`] on transport-level I/O failures.
574 pub async fn query_params(
575 &self,
576 query: &str,
577 params: &[&dyn crate::params::ToSqlParam],
578 ) -> Result<AsyncRowset<'_>> {
579 // Route through the extended query protocol. See
580 // [`Connection::query_params`] for the sync equivalent and the
581 // rationale behind the statement-guard pattern.
582 let client = match &self.transport {
583 AsyncTransport::Tcp(tcp) => &tcp.client,
584 AsyncTransport::Grpc(_) => {
585 return Err(Error::feature_not_supported(
586 "prepared statements are not supported over gRPC transport",
587 ));
588 }
589 };
590 let oids: Vec<crate::Oid> = params.iter().map(|p| p.sql_oid()).collect();
591 let stmt = client.prepare_typed(query, &oids).await?;
592 let encoded: Vec<Option<Vec<u8>>> = params.iter().map(|p| p.encode_param()).collect();
593 let stream = client
594 .execute_prepared_streaming(&stmt, encoded, crate::result::DEFAULT_BINARY_CHUNK_SIZE)
595 .await?;
596 Ok(AsyncRowset::from_prepared(stream).with_statement_guard(stmt))
597 }
598
599 /// Executes a parameterized command (INSERT / UPDATE / DELETE) with
600 /// binary-encoded parameters via Parse/Bind/Execute (async).
601 ///
602 /// # Errors
603 ///
604 /// - Returns [`Error::FeatureNotSupported`] on gRPC transports.
605 /// - Returns [`Error::Server`] if the server rejects the statement at
606 /// `Parse`, `Bind`, or `Execute` time.
607 /// - Returns [`Error::Io`] on transport-level I/O failures.
608 pub async fn command_params(
609 &self,
610 query: &str,
611 params: &[&dyn crate::params::ToSqlParam],
612 ) -> Result<u64> {
613 let client = match &self.transport {
614 AsyncTransport::Tcp(tcp) => &tcp.client,
615 AsyncTransport::Grpc(_) => {
616 return Err(Error::feature_not_supported(
617 "prepared statements are not supported over gRPC transport",
618 ));
619 }
620 };
621 let oids: Vec<crate::Oid> = params.iter().map(|p| p.sql_oid()).collect();
622 let stmt = client.prepare_typed(query, &oids).await?;
623 let encoded: Vec<Option<Vec<u8>>> = params.iter().map(|p| p.encode_param()).collect();
624 Ok(client.execute_prepared_no_result(&stmt, encoded).await?)
625 }
626
627 // =========================================================================
628 // Catalog / Database Management
629 // =========================================================================
630
631 /// Creates a new database file (async).
632 ///
633 /// # Errors
634 ///
635 /// Returns [`Error::Server`] if the server rejects
636 /// `CREATE DATABASE IF NOT EXISTS` (e.g. the path is not writable).
637 pub async fn create_database(&self, path: &str) -> Result<()> {
638 let sql = format!("CREATE DATABASE IF NOT EXISTS {}", escape_sql_path(path));
639 self.execute_command(&sql).await?;
640 Ok(())
641 }
642
643 /// Drops (deletes) a database file (async).
644 ///
645 /// # Errors
646 ///
647 /// Returns [`Error::Server`] if the server rejects
648 /// `DROP DATABASE IF EXISTS` (e.g. the database is still attached).
649 pub async fn drop_database(&self, path: &str) -> Result<()> {
650 let sql = format!("DROP DATABASE IF EXISTS {}", escape_sql_path(path));
651 self.execute_command(&sql).await?;
652 Ok(())
653 }
654
655 /// Attaches a database file to the connection (async).
656 ///
657 /// # Errors
658 ///
659 /// Returns [`Error::Server`] if the server rejects the
660 /// `ATTACH DATABASE` statement (file missing, permission denied,
661 /// alias conflict).
662 pub async fn attach_database(&self, path: &str, alias: Option<&str>) -> Result<()> {
663 let sql = if let Some(alias) = alias {
664 format!(
665 "ATTACH DATABASE {} AS {}",
666 escape_sql_path(path),
667 escape_sql_path(alias)
668 )
669 } else {
670 format!("ATTACH DATABASE {}", escape_sql_path(path))
671 };
672 self.execute_command(&sql).await?;
673 Ok(())
674 }
675
676 /// Detaches a database alias from this connection (async).
677 ///
678 /// # Errors
679 ///
680 /// Returns [`Error::Server`] if the alias is not attached or the
681 /// server cannot flush pending updates.
682 pub async fn detach_database(&self, alias: &str) -> Result<()> {
683 let sql = format!("DETACH DATABASE {}", escape_sql_path(alias));
684 self.execute_command(&sql).await?;
685 Ok(())
686 }
687
688 /// Detaches all databases from this connection (async).
689 ///
690 /// # Errors
691 ///
692 /// Returns [`Error::Server`] if the server rejects
693 /// `DETACH ALL DATABASES`.
694 pub async fn detach_all_databases(&self) -> Result<()> {
695 self.execute_command("DETACH ALL DATABASES").await?;
696 Ok(())
697 }
698
699 /// Copies a database file to a new path (async).
700 ///
701 /// # Errors
702 ///
703 /// Returns [`Error::Server`] if the server rejects the
704 /// `COPY DATABASE` statement — e.g. the source is not attached or the
705 /// destination path is not writable.
706 pub async fn copy_database(&self, source: &str, destination: &str) -> Result<()> {
707 let sql = format!(
708 "COPY DATABASE {} TO {}",
709 escape_sql_path(source),
710 escape_sql_path(destination)
711 );
712 self.execute_command(&sql).await?;
713 Ok(())
714 }
715
716 /// Creates a schema in the database (async).
717 ///
718 /// # Errors
719 ///
720 /// - Returns an error if `schema_name` cannot be converted to a
721 /// [`SchemaName`](crate::SchemaName).
722 /// - Returns [`Error::Server`] if the server rejects
723 /// `CREATE SCHEMA IF NOT EXISTS`.
724 pub async fn create_schema<T>(&self, schema_name: T) -> Result<()>
725 where
726 T: TryInto<crate::SchemaName>,
727 crate::Error: From<T::Error>,
728 {
729 let schema: crate::SchemaName = schema_name.try_into()?;
730 let sql = format!("CREATE SCHEMA IF NOT EXISTS {schema}");
731 self.execute_command(&sql).await?;
732 Ok(())
733 }
734
735 /// Checks whether a schema exists (async).
736 ///
737 /// # Errors
738 ///
739 /// - Returns an error if `schema` cannot be converted to a
740 /// [`SchemaName`](crate::SchemaName).
741 /// - Returns [`Error::Server`] if the catalog lookup query fails.
742 pub async fn has_schema<T>(&self, schema: T) -> Result<bool>
743 where
744 T: TryInto<crate::SchemaName>,
745 crate::Error: From<T::Error>,
746 {
747 let schema: crate::SchemaName = schema.try_into()?;
748 let db_prefix = if let Some(db) = schema.database() {
749 format!("{db}.")
750 } else {
751 String::new()
752 };
753 let sql = format!(
754 "SELECT 1 FROM {}pg_catalog.pg_namespace WHERE nspname = '{}'",
755 db_prefix,
756 schema.unescaped().replace('\'', "''")
757 );
758 Ok(self.fetch_optional(&sql).await?.is_some())
759 }
760
761 /// Checks whether a table exists (async).
762 ///
763 /// # Errors
764 ///
765 /// - Returns an error if `table_name` cannot be converted to a
766 /// [`TableName`](crate::TableName).
767 /// - Returns [`Error::Server`] if the catalog lookup query fails.
768 pub async fn has_table<T>(&self, table_name: T) -> Result<bool>
769 where
770 T: TryInto<crate::TableName>,
771 crate::Error: From<T::Error>,
772 {
773 let table: crate::TableName = table_name.try_into()?;
774 let schema = table
775 .schema()
776 .map_or("public", super::names::Name::unescaped);
777 let db_prefix = if let Some(db) = table.database() {
778 format!("{db}.")
779 } else {
780 String::new()
781 };
782 let sql = format!(
783 "SELECT 1 FROM {}pg_catalog.pg_tables WHERE schemaname = '{}' AND tablename = '{}'",
784 db_prefix,
785 schema.replace('\'', "''"),
786 table.table().unescaped().replace('\'', "''")
787 );
788 Ok(self.fetch_optional(&sql).await?.is_some())
789 }
790
791 /// Unloads the database from memory but keeps the session alive (async).
792 ///
793 /// # Errors
794 ///
795 /// Returns [`Error::Server`] if the server rejects `UNLOAD DATABASE`
796 /// (e.g. the database is in use by another session).
797 pub async fn unload_database(&self) -> Result<()> {
798 self.execute_command("UNLOAD DATABASE").await?;
799 Ok(())
800 }
801
802 /// Releases the database completely from the session (async).
803 ///
804 /// # Errors
805 ///
806 /// Returns [`Error::Server`] if the server rejects `UNLOAD RELEASE`,
807 /// most commonly because multiple databases are attached to the same
808 /// session.
809 pub async fn unload_release(&self) -> Result<()> {
810 self.execute_command("UNLOAD RELEASE").await?;
811 Ok(())
812 }
813
814 // =========================================================================
815 // Diagnostics / Explain
816 // =========================================================================
817
818 /// Executes EXPLAIN and returns the plan text (async).
819 ///
820 /// # Errors
821 ///
822 /// Returns [`Error::Server`] if `EXPLAIN <query>` fails to parse or plan.
823 pub async fn explain(&self, query: &str) -> Result<String> {
824 let sql = format!("EXPLAIN {query}");
825 let rows = self.fetch_all(&sql).await?;
826 let lines: Vec<String> = rows.iter().filter_map(|r| r.get::<String>(0)).collect();
827 Ok(lines.join("\n"))
828 }
829
830 /// Executes EXPLAIN ANALYZE and returns the plan with timing (async).
831 ///
832 /// # Errors
833 ///
834 /// Returns [`Error::Server`] if `EXPLAIN ANALYZE <query>` fails — this
835 /// includes any runtime error raised by actually executing `query`.
836 pub async fn explain_analyze(&self, query: &str) -> Result<String> {
837 let sql = format!("EXPLAIN ANALYZE {query}");
838 let rows = self.fetch_all(&sql).await?;
839 let lines: Vec<String> = rows.iter().filter_map(|r| r.get::<String>(0)).collect();
840 Ok(lines.join("\n"))
841 }
842
843 // =========================================================================
844 // Connection Introspection / Lifecycle
845 // =========================================================================
846
847 /// Returns true if the connection is alive (passive check).
848 pub fn is_alive(&self) -> bool {
849 match &self.transport {
850 AsyncTransport::Tcp(tcp) => tcp.client.is_alive(),
851 AsyncTransport::Grpc(_) => true,
852 }
853 }
854
855 /// Actively pings the server with `SELECT 1` (async).
856 ///
857 /// # Errors
858 ///
859 /// Returns [`Error::Server`] or [`Error::Io`] if the `SELECT 1`
860 /// round-trip fails — i.e. the connection is no longer usable.
861 pub async fn ping(&self) -> Result<()> {
862 self.execute_command("SELECT 1").await?;
863 Ok(())
864 }
865
866 /// Returns the backend process ID, or 0 for gRPC transports.
867 pub fn process_id(&self) -> i32 {
868 match &self.transport {
869 AsyncTransport::Tcp(tcp) => tcp.client.process_id(),
870 AsyncTransport::Grpc(_) => 0,
871 }
872 }
873
874 /// Returns the secret key used for cancel requests, or 0 for gRPC.
875 pub fn secret_key(&self) -> i32 {
876 match &self.transport {
877 AsyncTransport::Tcp(tcp) => tcp.client.secret_key(),
878 AsyncTransport::Grpc(_) => 0,
879 }
880 }
881
882 /// Returns a server parameter value by name (async).
883 pub async fn parameter_status(&self, name: &str) -> Option<String> {
884 match &self.transport {
885 AsyncTransport::Tcp(tcp) => tcp.client.parameter_status(name).await,
886 AsyncTransport::Grpc(_) => None,
887 }
888 }
889
890 /// Returns the server version as a parsed struct (async).
891 pub async fn server_version(&self) -> Option<crate::ServerVersion> {
892 let version_str = self.parameter_status("server_version").await?;
893 crate::ServerVersion::parse(&version_str)
894 }
895
896 /// Sets the notice receiver callback for this connection.
897 pub fn set_notice_receiver(
898 &mut self,
899 receiver: Option<Box<dyn Fn(hyperdb_api_core::client::Notice) + Send + Sync>>,
900 ) {
901 match &mut self.transport {
902 AsyncTransport::Tcp(tcp) => tcp.client.set_notice_receiver(receiver),
903 AsyncTransport::Grpc(_) => {}
904 }
905 }
906
907 /// Cancels the currently running query (async).
908 ///
909 /// # Errors
910 ///
911 /// - Returns [`Error::FeatureNotSupported`] on gRPC transports — cancellation is not
912 /// yet implemented for gRPC.
913 /// - Returns [`Error::Connection`] or [`Error::Io`] if the cancel-request
914 /// connection to the server fails.
915 pub async fn cancel(&self) -> Result<()> {
916 self.transport.cancel().await
917 }
918
919 /// Closes the connection gracefully, detaching any attached database first (async).
920 ///
921 /// # Errors
922 ///
923 /// - Returns [`Error::Internal`] wrapping the transport close failure if
924 /// the client cannot be shut down cleanly.
925 /// - Returns [`Error::Internal`] wrapping the detach failure if the
926 /// attached database could not be detached but the transport close
927 /// itself succeeded.
928 pub async fn close(self) -> Result<()> {
929 let detach_err = if let Some(ref db_path) = self.database {
930 let db_alias = std::path::Path::new(db_path)
931 .file_stem()
932 .and_then(|s| s.to_str())
933 .unwrap_or("db");
934 self.execute_command(&format!("DETACH DATABASE {}", escape_sql_path(db_alias)))
935 .await
936 .err()
937 } else {
938 None
939 };
940
941 let close_result = self.transport.close().await;
942
943 if let Err(e) = close_result {
944 return Err(Error::internal(format!(
945 "Failed to close async connection: {e}"
946 )));
947 }
948
949 if let Some(e) = detach_err {
950 return Err(Error::internal(format!(
951 "Failed to detach database during close: {e}"
952 )));
953 }
954
955 Ok(())
956 }
957
958 /// Returns a reference to the underlying async TCP client (`None` for gRPC).
959 ///
960 /// Prefer the high-level `AsyncConnection` methods; this escape hatch
961 /// remains for code that needs direct protocol access (e.g. custom
962 /// COPY loops).
963 pub fn async_tcp_client(&self) -> Option<&hyperdb_api_core::client::AsyncClient> {
964 self.transport.async_tcp_client()
965 }
966
967 /// Crate-internal accessor for the transport. Used by
968 /// [`AsyncPreparedStatement`](crate::AsyncPreparedStatement) to reach
969 /// the underlying `hyperdb_api_core::client::AsyncClient`.
970 pub(crate) fn transport(&self) -> &AsyncTransport {
971 &self.transport
972 }
973
974 /// Prepares a SQL statement (async).
975 ///
976 /// See [`Connection::prepare`](crate::Connection::prepare) for
977 /// semantics. The returned
978 /// [`AsyncPreparedStatement`](crate::AsyncPreparedStatement) can be
979 /// executed many times with different parameter values.
980 ///
981 /// # Errors
982 ///
983 /// See [`prepare_typed`](Self::prepare_typed) — this method delegates
984 /// to it with an empty OID list.
985 pub async fn prepare(&self, query: &str) -> Result<crate::AsyncPreparedStatement<'_>> {
986 self.prepare_typed(query, &[]).await
987 }
988
989 /// Prepares a SQL statement with explicit parameter type OIDs (async).
990 ///
991 /// # Errors
992 ///
993 /// - Returns [`Error::FeatureNotSupported`] on gRPC transports (prepared statements
994 /// are TCP-only).
995 /// - Returns [`Error::Server`] if the server rejects the `Parse`
996 /// message (SQL syntax error, unknown OID).
997 /// - Returns [`Error::Io`] on transport-level I/O failures.
998 pub async fn prepare_typed(
999 &self,
1000 query: &str,
1001 param_types: &[crate::Oid],
1002 ) -> Result<crate::AsyncPreparedStatement<'_>> {
1003 let client = match &self.transport {
1004 AsyncTransport::Tcp(tcp) => &tcp.client,
1005 AsyncTransport::Grpc(_) => {
1006 return Err(Error::feature_not_supported(
1007 "prepared statements are not supported over gRPC transport",
1008 ));
1009 }
1010 };
1011 let inner = client.prepare_typed(query, param_types).await?;
1012 crate::AsyncPreparedStatement::new(self, inner)
1013 }
1014
1015 /// Owned-handle variant of [`prepare`](Self::prepare). Returns a
1016 /// `'static`-lifetime [`AsyncPreparedStatementOwned`](crate::AsyncPreparedStatementOwned)
1017 /// that holds an `Arc`-cloned reference to `self`.
1018 ///
1019 /// Intended for N-API consumers and any other caller that needs
1020 /// the prepared statement to outlive the stack frame where the
1021 /// connection is held.
1022 ///
1023 /// # Errors
1024 ///
1025 /// See [`prepare_typed_arc`](Self::prepare_typed_arc).
1026 pub async fn prepare_arc(
1027 self: &Arc<Self>,
1028 query: &str,
1029 ) -> Result<crate::async_prepared::AsyncPreparedStatementOwned> {
1030 self.prepare_typed_arc(query, &[]).await
1031 }
1032
1033 /// Owned-handle variant of [`prepare_typed`](Self::prepare_typed).
1034 ///
1035 /// # Errors
1036 ///
1037 /// - Returns [`Error::FeatureNotSupported`] on gRPC transports.
1038 /// - Returns [`Error::Server`] if the server rejects the `Parse`
1039 /// message.
1040 /// - Returns [`Error::Io`] on transport-level I/O failures.
1041 pub async fn prepare_typed_arc(
1042 self: &Arc<Self>,
1043 query: &str,
1044 param_types: &[crate::Oid],
1045 ) -> Result<crate::async_prepared::AsyncPreparedStatementOwned> {
1046 let client = match &self.transport {
1047 AsyncTransport::Tcp(tcp) => &tcp.client,
1048 AsyncTransport::Grpc(_) => {
1049 return Err(Error::feature_not_supported(
1050 "prepared statements are not supported over gRPC transport",
1051 ));
1052 }
1053 };
1054 let inner = client.prepare_typed(query, param_types).await?;
1055 crate::async_prepared::AsyncPreparedStatementOwned::new(Arc::clone(self), inner)
1056 }
1057
1058 // =========================================================================
1059 // Query Statistics
1060 // =========================================================================
1061
1062 /// Enables query statistics collection for this connection.
1063 pub fn enable_query_stats(&self, provider: impl QueryStatsProvider + 'static) {
1064 if let Ok(mut guard) = self.stats_provider.lock() {
1065 *guard = Some(Arc::new(provider));
1066 }
1067 }
1068
1069 /// Disables query statistics collection.
1070 pub fn disable_query_stats(&self) {
1071 if let Ok(mut guard) = self.stats_provider.lock() {
1072 *guard = None;
1073 }
1074 if let Ok(mut guard) = self.pending_stats.lock() {
1075 *guard = None;
1076 }
1077 }
1078
1079 /// Returns the stats for the most recent query (if enabled).
1080 pub fn last_query_stats(&self) -> Option<QueryStats> {
1081 let provider = self.stats_provider.lock().ok()?.as_ref().cloned()?;
1082 let mut guard = self.pending_stats.lock().ok()?;
1083 let (token, sql) = guard.take()?;
1084 provider.after_query(token, &sql)
1085 }
1086
1087 fn stats_before_query(&self, sql: &str) -> Option<Box<dyn Any + Send>> {
1088 self.stats_provider
1089 .lock()
1090 .ok()?
1091 .as_ref()
1092 .map(|p| p.before_query(sql))
1093 }
1094
1095 fn stats_store_pending(&self, token: Option<Box<dyn Any + Send>>, sql: &str) {
1096 if let Some(token) = token {
1097 if let Ok(mut guard) = self.pending_stats.lock() {
1098 *guard = Some((token, sql.to_string()));
1099 }
1100 }
1101 }
1102}
1103
1104impl AsyncConnection {
1105 // =========================================================================
1106 // Transaction Control
1107 // =========================================================================
1108
1109 // -------------------------------------------------------------------
1110 // Raw transaction control (internal)
1111 // -------------------------------------------------------------------
1112 //
1113 // The `*_raw` methods below are `pub(crate)` and form the canonical
1114 // implementation of session-level transaction control. The RAII
1115 // guard at `crate::AsyncTransaction` and any internal helper that
1116 // genuinely needs `&self` (rather than the guard's `&mut self`)
1117 // delegate to these.
1118 //
1119 // The matching `pub` methods (`begin_transaction`, `commit`,
1120 // `rollback`) are thin `#[doc(hidden)] #[deprecated]` wrappers
1121 // retained only so any pre-existing downstream caller sees a
1122 // compiler warning rather than a hard break. They will be deleted
1123 // in a future release; the `_raw` methods stay.
1124
1125 /// Issues `BEGIN TRANSACTION`. Crate-internal use only.
1126 pub(crate) async fn begin_transaction_raw(&self) -> Result<()> {
1127 self.execute_command("BEGIN TRANSACTION").await?;
1128 Ok(())
1129 }
1130
1131 /// Issues `COMMIT`. Crate-internal use only.
1132 pub(crate) async fn commit_raw(&self) -> Result<()> {
1133 self.execute_command("COMMIT").await?;
1134 Ok(())
1135 }
1136
1137 /// Issues `ROLLBACK`. Crate-internal use only.
1138 pub(crate) async fn rollback_raw(&self) -> Result<()> {
1139 self.execute_command("ROLLBACK").await?;
1140 Ok(())
1141 }
1142
1143 /// Begins an explicit transaction (async).
1144 ///
1145 /// **Prefer [`transaction()`](Self::transaction)** — the RAII guard
1146 /// auto-rolls back on drop and cannot leak a half-open transaction
1147 /// across error paths. Hidden from generated rustdoc and
1148 /// deprecated; slated for removal in a future release.
1149 ///
1150 /// # Errors
1151 ///
1152 /// Returns [`Error::Server`] if the server rejects `BEGIN TRANSACTION`
1153 /// (e.g. a transaction is already open on this session).
1154 #[doc(hidden)]
1155 #[deprecated(
1156 note = "Use `AsyncConnection::transaction()` for an RAII guard. This method will be \
1157 removed in a future release."
1158 )]
1159 pub async fn begin_transaction(&self) -> Result<()> {
1160 self.begin_transaction_raw().await
1161 }
1162
1163 /// Commits the current transaction (async).
1164 ///
1165 /// **Prefer [`AsyncTransaction::commit`](crate::AsyncTransaction::commit)**
1166 /// on the RAII guard returned by [`transaction()`](Self::transaction).
1167 /// Hidden from generated rustdoc and deprecated; slated for removal.
1168 ///
1169 /// # Errors
1170 ///
1171 /// Returns [`Error::Server`] if the server rejects `COMMIT`.
1172 #[doc(hidden)]
1173 #[deprecated(note = "Use `AsyncTransaction::commit()` on the RAII guard from \
1174 `AsyncConnection::transaction()`. This method will be removed in a future release.")]
1175 pub async fn commit(&self) -> Result<()> {
1176 self.commit_raw().await
1177 }
1178
1179 /// Rolls back the current transaction (async).
1180 ///
1181 /// **Prefer [`AsyncTransaction::rollback`](crate::AsyncTransaction::rollback)**
1182 /// on the RAII guard returned by [`transaction()`](Self::transaction).
1183 /// Hidden from generated rustdoc and deprecated; slated for removal.
1184 ///
1185 /// # Errors
1186 ///
1187 /// Returns [`Error::Server`] if the server rejects `ROLLBACK`.
1188 #[doc(hidden)]
1189 #[deprecated(note = "Use `AsyncTransaction::rollback()` on the RAII guard from \
1190 `AsyncConnection::transaction()`. This method will be removed in a future release.")]
1191 pub async fn rollback(&self) -> Result<()> {
1192 self.rollback_raw().await
1193 }
1194
1195 /// Starts a transaction with an async RAII guard (async).
1196 ///
1197 /// # Errors
1198 ///
1199 /// Returns [`Error::Server`] if the internal `BEGIN` issued by
1200 /// [`AsyncTransaction::new`](crate::AsyncTransaction) fails.
1201 pub async fn transaction(&mut self) -> Result<crate::AsyncTransaction<'_>> {
1202 crate::AsyncTransaction::new(self).await
1203 }
1204}