Skip to main content

hyperdb_api/
connection.rs

1// Copyright (c) 2026, Salesforce, Inc. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Database connection management.
5//!
6//! The [`Connection`] type provides a unified interface for connecting to Hyper
7//! databases via either TCP (`PostgreSQL` wire protocol) or gRPC transport.
8//! The transport is automatically detected from the endpoint URL:
9//!
10//! - `https://` or `http://` → gRPC transport
11//! - Otherwise → TCP transport (e.g., `localhost:7483`)
12
13use std::path::Path;
14
15use hyperdb_api_core::client::Client;
16
17use crate::error::{Error, Result};
18use crate::names::escape_sql_path;
19use crate::process::HyperProcess;
20use crate::result::{DEFAULT_BINARY_CHUNK_SIZE, Row, Rowset};
21use crate::transport::Transport;
22
23use std::any::Any;
24use std::sync::{Arc, Mutex};
25
26use crate::query_stats::{QueryStats, QueryStatsProvider};
27
28/// Trait for types that can be extracted from a scalar query result.
29///
30/// This trait enables the generic [`Connection::execute_scalar_query`] method,
31/// similar to C++'s `executeScalarQuery<T>()` template.
32///
33/// # Implementing Custom Types
34///
35/// You can implement this trait for custom types to use them with `execute_scalar_query`:
36///
37/// ```no_run
38/// # use hyperdb_api::{Row, ScalarValue};
39/// # struct MyType;
40/// # impl MyType { fn parse(s: &str) -> Self { MyType } }
41/// impl ScalarValue for MyType {
42///     fn from_row(row: &Row, col: usize) -> Option<Self> {
43///         row.get_string(col).map(|s| MyType::parse(&s))
44///     }
45/// }
46/// ```
47pub trait ScalarValue: Sized {
48    /// Extracts a value of this type from a row at the given column.
49    fn from_row(row: &Row, col: usize) -> Option<Self>;
50}
51
52impl ScalarValue for i64 {
53    fn from_row(row: &Row, col: usize) -> Option<Self> {
54        row.get_i64(col)
55    }
56}
57
58impl ScalarValue for i32 {
59    fn from_row(row: &Row, col: usize) -> Option<Self> {
60        row.get_i32(col)
61    }
62}
63
64impl ScalarValue for i16 {
65    fn from_row(row: &Row, col: usize) -> Option<Self> {
66        row.get_i16(col)
67    }
68}
69
70impl ScalarValue for f64 {
71    fn from_row(row: &Row, col: usize) -> Option<Self> {
72        row.get_f64(col)
73    }
74}
75
76impl ScalarValue for bool {
77    fn from_row(row: &Row, col: usize) -> Option<Self> {
78        row.get_bool(col)
79    }
80}
81
82impl ScalarValue for String {
83    fn from_row(row: &Row, col: usize) -> Option<Self> {
84        row.get_string(col)
85    }
86}
87
88/// Database creation mode when connecting.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
90pub enum CreateMode {
91    /// Do not create the database. Method will fail if database doesn't exist.
92    #[default]
93    DoNotCreate,
94    /// Create the database. Method will fail if the database already exists.
95    Create,
96    /// Create the database if it doesn't exist.
97    CreateIfNotExists,
98    /// Create the database. If it already exists, drop the old one first.
99    CreateAndReplace,
100}
101
102/// A connection to a Hyper database.
103///
104/// This struct represents an active connection to a Hyper server and optionally
105/// an attached database. The connection is automatically closed when dropped.
106///
107/// # Transport Auto-Detection
108///
109/// The transport is automatically detected from the endpoint URL:
110/// - `https://` or `http://` → gRPC transport (read-only until server supports writes)
111/// - Otherwise → TCP transport (full read/write support)
112///
113/// # CSV / Text Import & Export
114///
115/// For CSV, TSV, and other delimited-text formats, see the [`copy`](crate::copy)
116/// module which provides [`export_csv()`](Self::export_csv),
117/// [`import_csv()`](Self::import_csv), and related methods on this struct.
118///
119/// # Example
120///
121/// ```no_run
122/// use hyperdb_api::{Connection, CreateMode, Result};
123///
124/// fn main() -> Result<()> {
125///     // TCP connection (full read/write)
126///     let conn = Connection::connect("localhost:7483", "example.hyper", CreateMode::CreateIfNotExists)?;
127///
128///     // Execute SQL commands
129///     conn.execute_command("CREATE TABLE test (id INT, name TEXT)")?;
130///     conn.execute_command("INSERT INTO test VALUES (1, 'Hello')")?;
131///
132///     Ok(())
133/// }
134/// ```
135///
136/// ```no_run
137/// # use hyperdb_api::{Connection, CreateMode, Result};
138/// # fn example() -> Result<()> {
139/// // gRPC connection (read-only, auto-detected from URL)
140/// let conn = Connection::connect(
141///     "https://hyper-server.example.com:443",
142///     "example.hyper",
143///     CreateMode::DoNotCreate,  // Must be DoNotCreate for gRPC
144/// )?;
145/// # Ok(())
146/// # }
147/// ```
148pub struct Connection {
149    transport: Transport,
150    database: Option<String>,
151    stats_provider: Option<Arc<dyn QueryStatsProvider>>,
152    /// Pending stats token + SQL from the most recent query, resolved lazily.
153    pending_stats: Mutex<Option<(Box<dyn Any + Send>, String)>>,
154}
155
156impl std::fmt::Debug for Connection {
157    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158        f.debug_struct("Connection")
159            .field("database", &self.database)
160            .finish_non_exhaustive()
161    }
162}
163
164impl Connection {
165    /// Creates a new connection to a Hyper instance with a database.
166    ///
167    /// This is the primary way to connect to a running [`HyperProcess`].
168    ///
169    /// # Arguments
170    ///
171    /// * `instance` - The Hyper server instance to connect to.
172    /// * `database_path` - Path to the database file.
173    /// * `create_mode` - How to handle database creation.
174    ///
175    /// # Errors
176    ///
177    /// Returns an error if the connection could not be established.
178    ///
179    /// # Example
180    ///
181    /// ```no_run
182    /// use hyperdb_api::{HyperProcess, Connection, CreateMode, Result};
183    ///
184    /// fn main() -> Result<()> {
185    ///     let hyper = HyperProcess::new(None, None)?;
186    ///     let conn = Connection::new(&hyper, "database.hyper", CreateMode::CreateIfNotExists)?;
187    ///     Ok(())
188    /// }
189    /// ```
190    pub fn new(
191        instance: &HyperProcess,
192        database_path: impl AsRef<Path>,
193        create_mode: CreateMode,
194    ) -> Result<Self> {
195        // Prefer using the connection_endpoint which properly handles UDS/Named Pipes
196        if let Some(conn_endpoint) = instance.connection_endpoint() {
197            return Self::connect_with_endpoint(
198                conn_endpoint,
199                &database_path.as_ref().to_string_lossy(),
200                create_mode,
201            );
202        }
203
204        // Fall back to string endpoint (TCP)
205        let endpoint = instance.require_endpoint()?;
206        Self::connect(
207            endpoint,
208            &database_path.as_ref().to_string_lossy(),
209            create_mode,
210        )
211    }
212
213    /// Connects using a `ConnectionEndpoint` (supports TCP, UDS, and Named Pipes).
214    fn connect_with_endpoint(
215        endpoint: &hyperdb_api_core::client::ConnectionEndpoint,
216        database_path: &str,
217        create_mode: CreateMode,
218    ) -> Result<Self> {
219        let db_path_str = Some(database_path.to_string());
220
221        let config = hyperdb_api_core::client::Config::new().with_user("tableau_internal_user");
222
223        let client = hyperdb_api_core::client::Client::connect_endpoint(endpoint, &config)?;
224
225        let conn = Connection::from_client(client, db_path_str.clone());
226
227        // Handle database creation
228        if let Some(db_path) = db_path_str {
229            conn.handle_creation_mode(&db_path, create_mode)?;
230            conn.attach_and_set_path(&db_path)?;
231        }
232
233        Ok(conn)
234    }
235
236    /// Connects to a Hyper server and optionally attaches a database.
237    ///
238    /// # Arguments
239    ///
240    /// * `endpoint` - The server endpoint (host:port).
241    /// * `database_path` - Path to the database file.
242    /// * `create_mode` - How to handle database creation.
243    ///
244    /// # Errors
245    ///
246    /// Returns an error if the connection could not be established.
247    pub fn connect(endpoint: &str, database_path: &str, create_mode: CreateMode) -> Result<Self> {
248        crate::ConnectionBuilder::new(endpoint)
249            .database(database_path)
250            .create_mode(create_mode)
251            .build()
252    }
253
254    /// Returns a connection builder for advanced configuration.
255    ///
256    /// This is useful when you need to set authentication, timeouts, or
257    /// other advanced options before connecting.
258    #[must_use]
259    pub fn builder(endpoint: &str) -> crate::ConnectionBuilder {
260        crate::ConnectionBuilder::new(endpoint)
261    }
262
263    /// Creates a Connection from a low-level Client (internal use, TCP only).
264    pub(crate) fn from_client(client: Client, database: Option<String>) -> Self {
265        Connection {
266            transport: Transport::Tcp(Box::new(crate::transport::TcpTransport { client })),
267            database,
268            stats_provider: None,
269            pending_stats: Mutex::new(None),
270        }
271    }
272
273    /// Creates a Connection from a Transport (internal use).
274    #[allow(
275        dead_code,
276        reason = "used by ConnectionBuilder for the gRPC path; not reached under non-gRPC feature builds"
277    )]
278    pub(crate) fn from_transport(transport: Transport, database: Option<String>) -> Self {
279        Connection {
280            transport,
281            database,
282            stats_provider: None,
283            pending_stats: Mutex::new(None),
284        }
285    }
286
287    /// Returns the transport type name (e.g., "TCP", "gRPC", "Unix Socket").
288    pub fn transport_type(&self) -> &'static str {
289        self.transport.transport_type().as_str()
290    }
291
292    /// Returns true if this connection supports write operations.
293    ///
294    /// Currently, only TCP connections support writes. gRPC connections are
295    /// read-only until the server supports write operations over gRPC.
296    pub fn supports_writes(&self) -> bool {
297        self.transport.supports_writes()
298    }
299
300    /// Handles database creation logic (internal use).
301    pub(crate) fn handle_creation_mode(
302        &self,
303        database_path: &str,
304        create_mode: CreateMode,
305    ) -> Result<()> {
306        match create_mode {
307            CreateMode::DoNotCreate => {}
308            CreateMode::Create => {
309                self.execute_command(&format!(
310                    "CREATE DATABASE {}",
311                    escape_sql_path(database_path)
312                ))?;
313            }
314            CreateMode::CreateIfNotExists => {
315                if let Err(e) = self.execute_command(&format!(
316                    "CREATE DATABASE IF NOT EXISTS {}",
317                    escape_sql_path(database_path)
318                )) && !is_already_exists_error(&e)
319                {
320                    return Err(Error::internal(format!(
321                        "Failed to create database '{database_path}': {e}"
322                    )));
323                }
324            }
325            CreateMode::CreateAndReplace => {
326                let _ = self.execute_command(&format!(
327                    "DROP DATABASE IF EXISTS {}",
328                    escape_sql_path(database_path)
329                ));
330                self.execute_command(&format!(
331                    "CREATE DATABASE {}",
332                    escape_sql_path(database_path)
333                ))?;
334            }
335        }
336        Ok(())
337    }
338
339    /// Attaches and sets the database path (internal use).
340    pub(crate) fn attach_and_set_path(&self, database_path: &str) -> Result<()> {
341        let db_alias = std::path::Path::new(database_path)
342            .file_stem()
343            .and_then(|s| s.to_str())
344            .unwrap_or("db");
345
346        self.execute_command(&format!(
347            "ATTACH DATABASE {} AS {}",
348            escape_sql_path(database_path),
349            escape_sql_path(db_alias)
350        ))?;
351
352        self.execute_command(&format!(
353            "SET search_path TO {}, public",
354            escape_sql_path(db_alias)
355        ))?;
356
357        Ok(())
358    }
359
360    /// Connects to a Hyper server with authentication.
361    ///
362    /// # Arguments
363    ///
364    /// * `endpoint` - The server endpoint (host:port).
365    /// * `database_path` - Path to the database file.
366    /// * `create_mode` - How to handle database creation.
367    /// * `user` - Username for authentication.
368    /// * `password` - Password for authentication.
369    ///
370    /// # Errors
371    ///
372    /// Returns an error if the connection or authentication fails.
373    pub fn connect_with_auth(
374        endpoint: &str,
375        database_path: &str,
376        create_mode: CreateMode,
377        user: &str,
378        password: &str,
379    ) -> Result<Self> {
380        crate::ConnectionBuilder::new(endpoint)
381            .database(database_path)
382            .create_mode(create_mode)
383            .user(user.to_string())
384            .password(password)
385            .build()
386    }
387
388    /// Creates a connection to a Hyper server without attaching a database.
389    ///
390    /// # Errors
391    ///
392    /// Returns [`Error::Connection`] if the TCP or gRPC handshake fails, and
393    /// [`Error::Io`] if the endpoint cannot be reached.
394    pub fn without_database(endpoint: &str) -> Result<Self> {
395        crate::ConnectionBuilder::new(endpoint).build()
396    }
397
398    /// Executes a SQL command that doesn't return results.
399    ///
400    /// Use this for DDL statements (CREATE, ALTER, DROP) and DML statements
401    /// (INSERT, UPDATE, DELETE).
402    ///
403    /// # Arguments
404    ///
405    /// * `command` - The SQL command to execute.
406    ///
407    /// # Returns
408    ///
409    /// The number of affected rows, or 0 if not applicable.
410    ///
411    /// # Errors
412    ///
413    /// Returns an error if:
414    /// - The connection is using gRPC transport (write operations not yet supported)
415    /// - The command fails to execute
416    pub fn execute_command(&self, command: &str) -> Result<u64> {
417        let token = self.stats_before_query(command);
418
419        let result = self.transport.execute_command(command);
420
421        // For commands, the query is fully executed synchronously, so we
422        // can store the pending token immediately for lazy resolution.
423        self.stats_store_pending(token, command);
424
425        result
426    }
427
428    /// Executes a SQL query and returns a streaming result set.
429    ///
430    /// Results are streamed in chunks (default 64K rows), keeping memory usage
431    /// constant regardless of result set size. This makes it safe for any
432    /// result size, from a single row to billions of rows.
433    ///
434    /// # Example
435    ///
436    /// ```no_run
437    /// # use hyperdb_api::{Connection, Result};
438    /// # fn example(conn: &Connection) -> Result<()> {
439    /// let mut result = conn.execute_query("SELECT id, value FROM measurements")?;
440    /// while let Some(chunk) = result.next_chunk()? {
441    ///     for row in &chunk {
442    ///         // Generic typed access (like C++ row.get<T>())
443    ///         let id: Option<i32> = row.get(0);
444    ///         let value: Option<f64> = row.get(1);
445    ///
446    ///         // Or direct accessors
447    ///         let id = row.get_i32(0);
448    ///         let value = row.get_f64(1);
449    ///     }
450    /// }
451    /// # Ok(())
452    /// # }
453    /// ```
454    ///
455    /// # Memory Behavior
456    ///
457    /// - Only one chunk is held in memory at a time (~few MB for 64K rows)
458    /// - Safe for result sets of any size (millions/billions of rows)
459    /// - Memory usage is `O(chunk_size)`, not `O(total_rows)`
460    ///
461    /// # Errors
462    ///
463    /// - Returns [`Error::Server`] wrapping a `hyperdb_api_core::client::Error` if the
464    ///   SQL fails to parse, execute, or if the server reports an error
465    ///   while streaming.
466    /// - Returns [`Error::Io`] on transport-level I/O failures.
467    pub fn execute_query(&self, query: &str) -> Result<Rowset<'_>> {
468        let token = self.stats_before_query(query);
469
470        let result = match &self.transport {
471            Transport::Tcp(tcp) => {
472                let stream = tcp
473                    .client
474                    .query_streaming(query, DEFAULT_BINARY_CHUNK_SIZE)?;
475                Ok(Rowset::new(stream))
476            }
477            Transport::Grpc(grpc) => {
478                // gRPC streaming: pull chunks lazily so peak memory is
479                // bounded by one gRPC message (tonic default 64 MB), not
480                // by the full result size. Matches TCP's
481                // constant-memory streaming shape.
482                //
483                // The transport module already creates a fresh gRPC client
484                // per query (gRPC client needs &mut self to execute), so we
485                // do the same here: connect, start the stream, wrap as a
486                // `ChunkSource`. The stream keeps the channel and runtime
487                // alive via refcounted handles inside `GrpcChunkStreamSync`.
488                let mut client =
489                    hyperdb_api_core::client::grpc::GrpcClientSync::connect(grpc.config.clone())?;
490                let stream = client.execute_query_stream(query)?;
491                let source = Box::new(crate::grpc_connection::GrpcChunkStreamSource::new(stream));
492                let arrow_rowset = crate::arrow_result::ArrowRowset::from_stream(source)?;
493                Ok(Rowset::from_arrow(arrow_rowset))
494            }
495        };
496
497        // Store the pending token — Hyper logs the execution stats after the
498        // result is consumed (streamed), so we defer resolution until
499        // last_query_stats() is called.
500        self.stats_store_pending(token, query);
501
502        result
503    }
504
505    // =========================================================================
506    // Arrow Format Queries
507    // =========================================================================
508
509    /// Executes a SELECT query and returns results as Arrow IPC stream bytes.
510    ///
511    /// # Example
512    ///
513    /// ```no_run
514    /// use hyperdb_api::{Connection, CreateMode, Result};
515    ///
516    /// fn main() -> Result<()> {
517    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::CreateIfNotExists)?;
518    ///
519    ///     // Create and populate a table
520    ///     conn.execute_command("CREATE TABLE data (id INT, value DOUBLE PRECISION)")?;
521    ///     conn.execute_command("INSERT INTO data VALUES (1, 1.5), (2, 2.5)")?;
522    ///
523    ///     // Get results as Arrow IPC stream
524    ///     let arrow_data = conn.execute_query_to_arrow("SELECT * FROM data")?;
525    ///     println!("Got {} bytes of Arrow IPC data", arrow_data.len());
526    ///
527    ///     Ok(())
528    /// }
529    /// ```
530    ///
531    /// # Errors
532    ///
533    /// Propagates any [`Error::Server`] from the TCP or gRPC transport when
534    /// the query fails or the server cannot produce Arrow IPC output.
535    pub fn execute_query_to_arrow(&self, select_query: &str) -> Result<bytes::Bytes> {
536        self.transport.execute_query_to_arrow(select_query)
537    }
538
539    /// Exports an entire table to Arrow IPC stream format.
540    ///
541    /// This is a convenience method equivalent to
542    /// `execute_query_to_arrow("SELECT * FROM table_name")`.
543    ///
544    /// # Arguments
545    ///
546    /// * `table_name` - The table name
547    ///
548    /// # Returns
549    ///
550    /// Raw Arrow IPC stream bytes containing all rows from the table.
551    ///
552    /// # Example
553    ///
554    /// ```no_run
555    /// use hyperdb_api::{Connection, CreateMode, Result};
556    ///
557    /// fn main() -> Result<()> {
558    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::CreateIfNotExists)?;
559    ///     let arrow_data = conn.export_table_to_arrow("my_table")?;
560    ///     Ok(())
561    /// }
562    /// ```
563    ///
564    /// # Errors
565    ///
566    /// Returns whatever [`execute_query_to_arrow`](Self::execute_query_to_arrow)
567    /// would return for `SELECT * FROM <table_name>` — typically
568    /// [`Error::Server`] if the table does not exist or the query is rejected.
569    pub fn export_table_to_arrow(&self, table_name: &str) -> Result<bytes::Bytes> {
570        self.execute_query_to_arrow(&format!("SELECT * FROM {table_name}"))
571    }
572
573    /// Executes a SELECT query and returns results as Arrow `RecordBatch`es.
574    ///
575    /// This is the recommended method for Arrow-native workflows (`DataFusion`,
576    /// Polars, etc.) where you want direct `RecordBatch` access without going
577    /// through the `Row` abstraction.
578    ///
579    /// # Example
580    ///
581    /// ```no_run
582    /// use hyperdb_api::{Connection, CreateMode, Result};
583    /// use arrow::record_batch::RecordBatch;
584    ///
585    /// fn main() -> Result<()> {
586    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::DoNotCreate)?;
587    ///
588    ///     let batches: Vec<RecordBatch> = conn.execute_query_to_batches("SELECT * FROM data")?;
589    ///     for batch in &batches {
590    ///         println!("batch: {} rows x {} cols", batch.num_rows(), batch.num_columns());
591    ///     }
592    ///     Ok(())
593    /// }
594    /// ```
595    ///
596    /// # Errors
597    ///
598    /// - Returns [`Error::Server`] if the query itself fails.
599    /// - Returns [`Error::Conversion`] if the Arrow IPC payload returned by the
600    ///   server is malformed and cannot be decoded into record batches.
601    pub fn execute_query_to_batches(
602        &self,
603        select_query: &str,
604    ) -> Result<Vec<arrow::record_batch::RecordBatch>> {
605        let arrow_data = self.execute_query_to_arrow(select_query)?;
606        crate::arrow_result::parse_arrow_ipc(arrow_data)
607    }
608
609    /// Fetches a single row from a query.
610    ///
611    /// Returns an error if the query returns no rows.
612    ///
613    /// # Example
614    ///
615    /// ```no_run
616    /// use hyperdb_api::{Connection, CreateMode, Result};
617    ///
618    /// fn main() -> Result<()> {
619    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::DoNotCreate)?;
620    ///     let row = conn.fetch_one("SELECT * FROM users WHERE id = 1")?;
621    ///     let id: Option<i32> = row.get(0);
622    ///     let name: Option<String> = row.get(1);
623    ///     Ok(())
624    /// }
625    /// ```
626    ///
627    /// # Errors
628    ///
629    /// - Returns the error from [`execute_query`](Self::execute_query) if
630    ///   the query itself fails.
631    /// - Returns [`Error::Conversion`] with message `"Query returned no rows"` if
632    ///   the query produced zero rows.
633    pub fn fetch_one<Q>(&self, query: Q) -> Result<crate::Row>
634    where
635        Q: AsRef<str>,
636    {
637        let query = query.as_ref();
638        let result = self.execute_query(query)?;
639        result.require_first_row()
640    }
641
642    /// Fetches an optional single row from a query.
643    ///
644    /// Returns `None` if the query returns no rows.
645    ///
646    /// # Example
647    ///
648    /// ```no_run
649    /// use hyperdb_api::{Connection, CreateMode, Result};
650    ///
651    /// fn main() -> Result<()> {
652    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::DoNotCreate)?;
653    ///     if let Some(row) = conn.fetch_optional("SELECT * FROM users WHERE id = 999")? {
654    ///         let name: Option<String> = row.get(1);
655    ///         println!("Found user: {:?}", name);
656    ///     }
657    ///     Ok(())
658    /// }
659    /// ```
660    ///
661    /// # Errors
662    ///
663    /// Returns the error from [`execute_query`](Self::execute_query) if the
664    /// query itself fails. An empty result set is not an error — it yields
665    /// `Ok(None)`.
666    pub fn fetch_optional<Q>(&self, query: Q) -> Result<Option<crate::Row>>
667    where
668        Q: AsRef<str>,
669    {
670        let query = query.as_ref();
671        let result = self.execute_query(query)?;
672        result.first_row()
673    }
674
675    /// Fetches all rows from a query.
676    ///
677    /// # Example
678    ///
679    /// ```no_run
680    /// use hyperdb_api::{Connection, CreateMode, Result};
681    ///
682    /// fn main() -> Result<()> {
683    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::DoNotCreate)?;
684    ///     let rows = conn.fetch_all("SELECT * FROM users WHERE active = true ORDER BY name")?;
685    ///     for row in rows {
686    ///         let id: Option<i32> = row.get(0);
687    ///         let name: Option<String> = row.get(1);
688    ///         println!("User {}: {:?}", id.unwrap_or(-1), name);
689    ///     }
690    ///     Ok(())
691    /// }
692    /// ```
693    ///
694    /// # Errors
695    ///
696    /// Returns the error from [`execute_query`](Self::execute_query), or a
697    /// transport error produced while draining every chunk of the streamed
698    /// result set.
699    pub fn fetch_all<Q>(&self, query: Q) -> Result<Vec<crate::Row>>
700    where
701        Q: AsRef<str>,
702    {
703        let query = query.as_ref();
704        let result = self.execute_query(query)?;
705        result.collect_rows()
706    }
707
708    /// Fetches a single row and maps it to a struct using [`FromRow`](crate::FromRow).
709    ///
710    /// Returns an error if the query returns no rows or if mapping fails.
711    ///
712    /// # Example
713    ///
714    /// ```no_run
715    /// use hyperdb_api::{Connection, CreateMode, FromRow, RowAccessor, Result};
716    ///
717    /// struct User { id: i32, name: String }
718    ///
719    /// impl FromRow for User {
720    ///     fn from_row(row: RowAccessor<'_>) -> Result<Self> {
721    ///         Ok(User {
722    ///             id: row.get("id")?,
723    ///             name: row.get_opt("name")?.unwrap_or_default(),
724    ///         })
725    ///     }
726    /// }
727    ///
728    /// fn main() -> Result<()> {
729    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::DoNotCreate)?;
730    ///     let user: User = conn.fetch_one_as("SELECT id, name FROM users WHERE id = 1")?;
731    ///     Ok(())
732    /// }
733    /// ```
734    ///
735    /// # Errors
736    ///
737    /// - Returns the error from [`fetch_one`](Self::fetch_one) if the query
738    ///   fails or returns no rows.
739    /// - Returns whatever error [`FromRow::from_row`](crate::FromRow::from_row)
740    ///   produces when the row cannot be mapped into `T`.
741    pub fn fetch_one_as<T: crate::FromRow>(&self, query: &str) -> Result<T> {
742        let row = self.fetch_one(query)?;
743        let indices = row
744            .schema()
745            .map(crate::row_accessor::RowAccessor::build_indices)
746            .unwrap_or_default();
747        T::from_row(crate::RowAccessor::new(&row, &indices))
748    }
749
750    /// Fetches all rows and maps them to structs using [`FromRow`](crate::FromRow).
751    ///
752    /// # Example
753    ///
754    /// ```no_run
755    /// # use hyperdb_api::{Connection, FromRow, RowAccessor, Result};
756    /// # struct User { id: i32, name: String }
757    /// # impl FromRow for User {
758    /// #     fn from_row(row: RowAccessor<'_>) -> Result<Self> {
759    /// #         Ok(User { id: row.get("id")?, name: row.get_opt("name")?.unwrap_or_default() })
760    /// #     }
761    /// # }
762    /// # fn example(conn: &Connection) -> Result<()> {
763    /// let users: Vec<User> = conn.fetch_all_as("SELECT id, name FROM users")?;
764    /// # Ok(())
765    /// # }
766    /// ```
767    ///
768    /// # Errors
769    ///
770    /// - Returns the error from [`fetch_all`](Self::fetch_all) if the query
771    ///   fails.
772    /// - Returns the first error produced by
773    ///   [`FromRow::from_row`](crate::FromRow::from_row) on any of the rows.
774    pub fn fetch_all_as<T: crate::FromRow>(&self, query: &str) -> Result<Vec<T>> {
775        let rows = self.fetch_all(query)?;
776        // Build the column-name → index lookup once from the first
777        // row's schema; reuse for every row. All rows in a result set
778        // share the same `Arc<ResultSchema>`, so this is safe.
779        let indices = rows
780            .first()
781            .and_then(crate::result::Row::schema)
782            .map(crate::row_accessor::RowAccessor::build_indices)
783            .unwrap_or_default();
784        rows.iter()
785            .map(|r| T::from_row(crate::RowAccessor::new(r, &indices)))
786            .collect()
787    }
788
789    /// Returns a lazy iterator over rows, mapping each to `T` via
790    /// [`FromRow`].
791    ///
792    /// This is the streaming variant of [`fetch_all_as`](Self::fetch_all_as):
793    /// memory usage is bounded by the chunk size (default 64K rows), not by
794    /// the total row count. Use this for large result sets where collecting
795    /// all rows into a `Vec` would exceed memory limits.
796    ///
797    /// The column-name → index lookup table is built exactly once (on the
798    /// first non-empty chunk) and reused for all rows, so per-row mapping is
799    /// O(1) in column count.
800    ///
801    /// # Example
802    ///
803    /// ```no_run
804    /// # use hyperdb_api::{Connection, CreateMode, FromRow, RowAccessor, Result};
805    /// # struct User { id: i32, name: String }
806    /// # impl FromRow for User {
807    /// #     fn from_row(row: RowAccessor<'_>) -> Result<Self> {
808    /// #         Ok(User { id: row.get("id")?, name: row.get("name")? })
809    /// #     }
810    /// # }
811    /// # fn example(conn: &Connection) -> Result<()> {
812    /// for row_result in conn.stream_as::<User>("SELECT id, name FROM users")? {
813    ///     let user = row_result?;
814    ///     println!("{}: {}", user.id, user.name);
815    /// }
816    /// # Ok(())
817    /// # }
818    /// ```
819    ///
820    /// # Errors
821    ///
822    /// - The returned `Result` wraps errors detected while *opening* the
823    ///   result stream — transport/connection failures, and (on the gRPC
824    ///   transport, which establishes the query stream eagerly) SQL parse and
825    ///   server errors. On the default TCP transport the query is streamed
826    ///   lazily, so SQL errors such as a missing table are typically reported
827    ///   as the **first yielded item** rather than by this outer `Result`.
828    /// - Each yielded item is itself a `Result<T>`:
829    ///   - `Ok(T)` if the row was successfully mapped via `FromRow`.
830    ///   - `Err(e)` for a server/transport error encountered while streaming a
831    ///     later chunk, or for a per-row mapping failure (missing column, type
832    ///     mismatch, NULL in a non-optional field).
833    ///
834    /// In short: always handle errors *both* on the outer `Result` and on each
835    /// item — do not assume a successfully-returned iterator means the query
836    /// succeeded.
837    ///
838    /// [`FromRow`]: crate::FromRow
839    pub fn stream_as<'a, T>(
840        &'a self,
841        query: &str,
842    ) -> Result<impl Iterator<Item = Result<T>> + 'a + use<'a, T>>
843    where
844        T: crate::FromRow + 'a,
845    {
846        let rowset = self.execute_query(query)?;
847        Ok(crate::result::TypedRowIterator::<T>::new(rowset))
848    }
849
850    /// Fetches a single row from a **parameterized** query and maps it to a
851    /// struct using [`FromRow`](crate::FromRow).
852    ///
853    /// This is the parameterized counterpart to
854    /// [`fetch_one_as`](Self::fetch_one_as): it binds `$1`, `$2`, … placeholders
855    /// from `params` (via [`ToSqlParam`](crate::params::ToSqlParam), exactly as
856    /// [`query_params`](Self::query_params) does) and maps the first result row
857    /// into `T`. Use it when a parameterized `SELECT` should yield a typed
858    /// struct rather than a raw [`Row`](crate::Row).
859    ///
860    /// # Example
861    ///
862    /// ```no_run
863    /// # use hyperdb_api::{Connection, FromRow, RowAccessor, Result};
864    /// # struct User { id: i32, name: String }
865    /// # impl FromRow for User {
866    /// #     fn from_row(row: RowAccessor<'_>) -> Result<Self> {
867    /// #         Ok(User { id: row.get("id")?, name: row.get("name")? })
868    /// #     }
869    /// # }
870    /// # fn example(conn: &Connection) -> Result<()> {
871    /// let user: User = conn.fetch_one_as_params(
872    ///     "SELECT id, name FROM users WHERE id = $1",
873    ///     &[&1i32],
874    /// )?;
875    /// # Ok(())
876    /// # }
877    /// ```
878    ///
879    /// # Errors
880    ///
881    /// - Returns [`Error::FeatureNotSupported`] if the connection is using gRPC
882    ///   transport (prepared statements are TCP-only).
883    /// - Returns the error from [`query_params`](Self::query_params) if the
884    ///   server rejects the statement at `Parse`, `Bind`, or `Execute` time, or
885    ///   on transport-level I/O failures.
886    /// - Returns [`Error::Conversion`] with message `"Query returned no rows"`
887    ///   if the query produced zero rows.
888    /// - Returns whatever [`FromRow::from_row`](crate::FromRow::from_row)
889    ///   produces when the row cannot be mapped into `T`.
890    pub fn fetch_one_as_params<T: crate::FromRow>(
891        &self,
892        query: &str,
893        params: &[&dyn crate::params::ToSqlParam],
894    ) -> Result<T> {
895        let row = self.query_params(query, params)?.require_first_row()?;
896        let indices = row
897            .schema()
898            .map(crate::row_accessor::RowAccessor::build_indices)
899            .unwrap_or_default();
900        T::from_row(crate::RowAccessor::new(&row, &indices))
901    }
902
903    /// Fetches all rows from a **parameterized** query and maps them to structs
904    /// using [`FromRow`](crate::FromRow).
905    ///
906    /// This is the parameterized counterpart to
907    /// [`fetch_all_as`](Self::fetch_all_as): it binds `$1`, `$2`, … placeholders
908    /// from `params` (see [`query_params`](Self::query_params)) and maps every
909    /// result row into `T`.
910    ///
911    /// # Example
912    ///
913    /// ```no_run
914    /// # use hyperdb_api::{Connection, FromRow, RowAccessor, Result};
915    /// # struct User { id: i32, name: String }
916    /// # impl FromRow for User {
917    /// #     fn from_row(row: RowAccessor<'_>) -> Result<Self> {
918    /// #         Ok(User { id: row.get("id")?, name: row.get("name")? })
919    /// #     }
920    /// # }
921    /// # fn example(conn: &Connection) -> Result<()> {
922    /// let users: Vec<User> = conn.fetch_all_as_params(
923    ///     "SELECT id, name FROM users WHERE org_id = $1",
924    ///     &[&42i32],
925    /// )?;
926    /// # Ok(())
927    /// # }
928    /// ```
929    ///
930    /// # Errors
931    ///
932    /// - Returns [`Error::FeatureNotSupported`] if the connection is using gRPC
933    ///   transport.
934    /// - Returns the error from [`query_params`](Self::query_params) if the
935    ///   server rejects the statement, or on transport-level I/O failures.
936    /// - Returns the first error produced by
937    ///   [`FromRow::from_row`](crate::FromRow::from_row) on any of the rows.
938    pub fn fetch_all_as_params<T: crate::FromRow>(
939        &self,
940        query: &str,
941        params: &[&dyn crate::params::ToSqlParam],
942    ) -> Result<Vec<T>> {
943        let rows = self.query_params(query, params)?.collect_rows()?;
944        // Build the column-name → index lookup once from the first row's
945        // schema; reuse for every row. See `fetch_all_as`.
946        let indices = rows
947            .first()
948            .and_then(crate::result::Row::schema)
949            .map(crate::row_accessor::RowAccessor::build_indices)
950            .unwrap_or_default();
951        rows.iter()
952            .map(|r| T::from_row(crate::RowAccessor::new(r, &indices)))
953            .collect()
954    }
955
956    /// Returns a lazy iterator over the rows of a **parameterized** query,
957    /// mapping each to `T` via [`FromRow`].
958    ///
959    /// This is the parameterized counterpart to
960    /// [`stream_as`](Self::stream_as): it binds `$1`, `$2`, … placeholders from
961    /// `params` (see [`query_params`](Self::query_params)) and streams the
962    /// result, mapping each row into `T` while holding only one transport chunk
963    /// in memory at a time. The column-index map is built once on the first
964    /// chunk and reused, so per-row mapping is O(1) in the column count.
965    ///
966    /// # Example
967    ///
968    /// ```no_run
969    /// # use hyperdb_api::{Connection, FromRow, RowAccessor, Result};
970    /// # struct User { id: i32, name: String }
971    /// # impl FromRow for User {
972    /// #     fn from_row(row: RowAccessor<'_>) -> Result<Self> {
973    /// #         Ok(User { id: row.get("id")?, name: row.get("name")? })
974    /// #     }
975    /// # }
976    /// # fn example(conn: &Connection) -> Result<()> {
977    /// for row_result in conn.stream_as_params::<User>(
978    ///     "SELECT id, name FROM users WHERE org_id = $1",
979    ///     &[&42i32],
980    /// )? {
981    ///     let user = row_result?;
982    ///     println!("{}: {}", user.id, user.name);
983    /// }
984    /// # Ok(())
985    /// # }
986    /// ```
987    ///
988    /// # Errors
989    ///
990    /// - The returned outer `Result` wraps errors detected while *opening* the
991    ///   stream: [`Error::FeatureNotSupported`] on gRPC transport, and any
992    ///   `Parse`/`Bind` rejection or transport failure surfaced by
993    ///   [`query_params`](Self::query_params).
994    /// - Each yielded item is itself a `Result<T>`: `Ok(T)` when the row mapped
995    ///   cleanly, or `Err(e)` for a per-row mapping failure (missing column,
996    ///   type mismatch, NULL in a non-optional field) or a server/transport
997    ///   error hit while streaming a later chunk.
998    ///
999    /// As with [`stream_as`](Self::stream_as), always handle errors *both* on
1000    /// the outer `Result` and on each item.
1001    ///
1002    /// [`FromRow`]: crate::FromRow
1003    pub fn stream_as_params<'a, T>(
1004        &'a self,
1005        query: &str,
1006        params: &[&dyn crate::params::ToSqlParam],
1007    ) -> Result<impl Iterator<Item = Result<T>> + 'a + use<'a, T>>
1008    where
1009        T: crate::FromRow + 'a,
1010    {
1011        // `query_params` returns a Rowset that already carries the prepared
1012        // statement guard, so Drop ordering (close_statement after the rowset
1013        // releases its connection lock) is preserved with no extra work here.
1014        let rowset = self.query_params(query, params)?;
1015        Ok(crate::result::TypedRowIterator::<T>::new(rowset))
1016    }
1017
1018    /// Fetches a single scalar value from a query.
1019    ///
1020    /// Returns an error if the query returns no rows or NULL.
1021    ///
1022    /// # Example
1023    ///
1024    /// ```no_run
1025    /// use hyperdb_api::{Connection, CreateMode, Result};
1026    ///
1027    /// fn main() -> Result<()> {
1028    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::DoNotCreate)?;
1029    ///     let count: i64 = conn.fetch_scalar("SELECT COUNT(*) FROM users")?;
1030    ///     println!("User count: {}", count);
1031    ///     Ok(())
1032    /// }
1033    /// ```
1034    ///
1035    /// # Errors
1036    ///
1037    /// - Returns the error from [`execute_query`](Self::execute_query) if
1038    ///   the query itself fails.
1039    /// - Returns [`Error::Conversion`] with message `"Query returned no rows"` if
1040    ///   the query produced zero rows.
1041    /// - Returns [`Error::Conversion`] with message `"Scalar query returned NULL"`
1042    ///   if the single cell is SQL `NULL`.
1043    pub fn fetch_scalar<T, Q>(&self, query: Q) -> Result<T>
1044    where
1045        T: crate::connection::ScalarValue + crate::result::RowValue,
1046        Q: AsRef<str>,
1047    {
1048        let query = query.as_ref();
1049        let result = self.execute_query(query)?;
1050        result.require_scalar()
1051    }
1052
1053    /// Fetches an optional scalar value from a query.
1054    ///
1055    /// Returns `None` if the query returns no rows or NULL.
1056    ///
1057    /// # Example
1058    ///
1059    /// ```no_run
1060    /// use hyperdb_api::{Connection, CreateMode, Result};
1061    ///
1062    /// fn main() -> Result<()> {
1063    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::DoNotCreate)?;
1064    ///     let max_id: Option<i32> = conn.fetch_optional_scalar("SELECT MAX(id) FROM users")?;
1065    ///     println!("Max ID: {:?}", max_id);
1066    ///     Ok(())
1067    /// }
1068    /// ```
1069    ///
1070    /// # Errors
1071    ///
1072    /// - Returns the error from [`execute_query`](Self::execute_query) if
1073    ///   the query itself fails.
1074    /// - Returns [`Error::Conversion`] with message `"Query returned no rows"` if
1075    ///   the query produced zero rows. (An empty result is treated as an
1076    ///   error here because we need at least one row to inspect; SQL `NULL`
1077    ///   in the single cell yields `Ok(None)`.)
1078    pub fn fetch_optional_scalar<T, Q>(&self, query: Q) -> Result<Option<T>>
1079    where
1080        T: crate::connection::ScalarValue + crate::result::RowValue,
1081        Q: AsRef<str>,
1082    {
1083        let query = query.as_ref();
1084        let result = self.execute_query(query)?;
1085        result.scalar()
1086    }
1087
1088    /// Executes a scalar query and returns a single value of type `T`.
1089    ///
1090    /// Alias for [`fetch_optional_scalar`](Self::fetch_optional_scalar) for C++ API compatibility.
1091    ///
1092    /// # Errors
1093    ///
1094    /// See [`fetch_optional_scalar`](Self::fetch_optional_scalar).
1095    #[inline]
1096    pub fn execute_scalar_query<T>(&self, query: &str) -> Result<Option<T>>
1097    where
1098        T: ScalarValue + crate::result::RowValue,
1099    {
1100        self.fetch_optional_scalar(query)
1101    }
1102
1103    /// Queries for a count value, defaulting to 0 if NULL.
1104    ///
1105    /// This is optimized for COUNT queries which typically return 0
1106    /// instead of NULL when there are no matching rows.
1107    ///
1108    /// # Example
1109    ///
1110    /// ```no_run
1111    /// use hyperdb_api::{Connection, CreateMode, Result};
1112    ///
1113    /// fn main() -> Result<()> {
1114    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::DoNotCreate)?;
1115    ///     let count = conn.query_count("SELECT COUNT(*) FROM users WHERE active = true")?;
1116    ///     println!("Active users: {}", count);
1117    ///     Ok(())
1118    /// }
1119    /// ```
1120    ///
1121    /// # Errors
1122    ///
1123    /// Returns the error from [`execute_query`](Self::execute_query) if the
1124    /// query fails or produces no rows. SQL `NULL` is mapped to `0`, not an
1125    /// error.
1126    pub fn query_count(&self, query: &str) -> Result<i64> {
1127        self.fetch_optional_scalar::<i64, _>(query)
1128            .map(|opt| opt.unwrap_or(0))
1129    }
1130
1131    // =========================================================================
1132    // Parameterized Queries (SQL Injection Safe)
1133    // =========================================================================
1134
1135    /// Executes a parameterized query, returning streaming results.
1136    ///
1137    /// This is safe to use with untrusted user input: parameters travel
1138    /// through the extended query protocol (Parse/Bind/Execute) as
1139    /// binary `HyperBinary` values and are never interpolated into the
1140    /// SQL string. For repeated executions of the same SQL with different
1141    /// values, prefer the explicit [`prepare`](Self::prepare) API — it
1142    /// returns a reusable [`PreparedStatement`](crate::PreparedStatement)
1143    /// that skips the Parse round-trip on every call.
1144    ///
1145    /// Under the hood, `query_params` is a one-shot
1146    /// prepare+execute+close: it prepares an unnamed statement, binds
1147    /// the parameters, starts streaming, and closes the statement when
1148    /// the returned [`Rowset`] is dropped.
1149    ///
1150    /// # Arguments
1151    ///
1152    /// * `query` - The SQL query with parameter placeholders (`$1`, `$2`, etc.)
1153    /// * `params` - Parameter values matching the placeholders
1154    ///
1155    /// # SQL Injection Prevention
1156    ///
1157    /// ```no_run
1158    /// use hyperdb_api::{Connection, CreateMode, Result};
1159    ///
1160    /// fn search_users(conn: &Connection, user_input: &str) -> Result<()> {
1161    ///     // DANGEROUS - vulnerable to SQL injection:
1162    ///     // let query = format!("SELECT * FROM users WHERE name = '{}'", user_input);
1163    ///
1164    ///     // SAFE - parameterized query:
1165    ///     let mut result = conn.query_params(
1166    ///         "SELECT * FROM users WHERE name = $1",
1167    ///         &[&user_input],
1168    ///     )?;
1169    ///
1170    ///     while let Some(chunk) = result.next_chunk()? {
1171    ///         for row in &chunk {
1172    ///             let id: Option<i32> = row.get(0);
1173    ///             let name: Option<String> = row.get(1);
1174    ///             println!("Found: {:?} - {:?}", id, name);
1175    ///         }
1176    ///     }
1177    ///     Ok(())
1178    /// }
1179    /// ```
1180    ///
1181    /// # Multiple Parameters
1182    ///
1183    /// ```no_run
1184    /// use hyperdb_api::{Connection, CreateMode, Result};
1185    ///
1186    /// fn main() -> Result<()> {
1187    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::DoNotCreate)?;
1188    ///
1189    ///     // Multiple parameters of different types
1190    ///     let result = conn.query_params(
1191    ///         "SELECT * FROM orders WHERE customer_id = $1 AND total > $2",
1192    ///         &[&42i32, &100.0f64],
1193    ///     )?;
1194    ///     Ok(())
1195    /// }
1196    /// ```
1197    ///
1198    /// # Errors
1199    ///
1200    /// - Returns [`Error::FeatureNotSupported`] if the connection is using gRPC transport
1201    ///   (prepared statements are TCP-only).
1202    /// - Returns [`Error::Server`] if the server rejects the statement at
1203    ///   `Parse`, `Bind`, or `Execute` time, including on type-mismatch
1204    ///   between `params` and the inferred OIDs.
1205    /// - Returns [`Error::Io`] on transport-level I/O failures.
1206    pub fn query_params(
1207        &self,
1208        query: &str,
1209        params: &[&dyn crate::params::ToSqlParam],
1210    ) -> Result<Rowset<'_>> {
1211        // Implementation note: routes through the extended query protocol
1212        // via Parse/Bind/Execute so parameters travel in HyperBinary
1213        // format — no SQL escaping, full SQL-injection safety regardless of
1214        // parameter content. The statement handle is stashed inside the
1215        // returned Rowset so its Drop-time close_statement fires *after*
1216        // the rowset releases its connection lock (otherwise the close
1217        // would deadlock on the still-held mutex).
1218        let client = match &self.transport {
1219            Transport::Tcp(tcp) => &tcp.client,
1220            Transport::Grpc(_) => {
1221                return Err(Error::feature_not_supported(
1222                    "prepared statements are not supported over gRPC transport",
1223                ));
1224            }
1225        };
1226        let oids: Vec<crate::Oid> = params.iter().map(|p| p.sql_oid()).collect();
1227        let stmt = client.prepare_typed(query, &oids)?;
1228        let encoded: Vec<Option<Vec<u8>>> = params.iter().map(|p| p.encode_param()).collect();
1229        let stream =
1230            client.execute_streaming(&stmt, encoded, crate::result::DEFAULT_BINARY_CHUNK_SIZE)?;
1231        Ok(Rowset::from_prepared(stream).with_statement_guard(stmt))
1232    }
1233
1234    /// Executes a parameterized command that doesn't return rows.
1235    ///
1236    /// Use this for INSERT, UPDATE, DELETE, or DDL statements with parameters.
1237    /// Returns the number of affected rows.
1238    ///
1239    /// See [`query_params`](Self::query_params) for details on parameter
1240    /// handling and SQL injection prevention.
1241    ///
1242    /// # Example
1243    ///
1244    /// ```no_run
1245    /// use hyperdb_api::{Connection, CreateMode, Result};
1246    ///
1247    /// fn delete_user(conn: &Connection, user_id: i32) -> Result<u64> {
1248    ///     // Safe from SQL injection
1249    ///     conn.command_params("DELETE FROM users WHERE id = $1", &[&user_id])
1250    /// }
1251    /// ```
1252    ///
1253    /// # Errors
1254    ///
1255    /// - Returns [`Error::FeatureNotSupported`] if the connection is using gRPC transport.
1256    /// - Returns [`Error::Server`] if the server rejects the statement at
1257    ///   `Parse`, `Bind`, or `Execute` time.
1258    /// - Returns [`Error::Io`] on transport-level I/O failures.
1259    pub fn command_params(
1260        &self,
1261        query: &str,
1262        params: &[&dyn crate::params::ToSqlParam],
1263    ) -> Result<u64> {
1264        // One-shot prepare+execute with explicit OIDs — see `query_params`
1265        // for why we collect OIDs from each parameter.
1266        let client = match &self.transport {
1267            Transport::Tcp(tcp) => &tcp.client,
1268            Transport::Grpc(_) => {
1269                return Err(Error::feature_not_supported(
1270                    "prepared statements are not supported over gRPC transport",
1271                ));
1272            }
1273        };
1274        let oids: Vec<crate::Oid> = params.iter().map(|p| p.sql_oid()).collect();
1275        let stmt = client.prepare_typed(query, &oids)?;
1276        let encoded: Vec<Option<Vec<u8>>> = params.iter().map(|p| p.encode_param()).collect();
1277        Ok(client.execute_no_result(&stmt, encoded)?)
1278    }
1279
1280    /// Executes multiple SQL statements in a single call.
1281    ///
1282    /// Each statement is executed sequentially. If any statement fails,
1283    /// execution stops and the error is returned. Returns the total number
1284    /// of affected rows across all statements.
1285    ///
1286    /// This is more efficient than calling `execute_command` in a loop
1287    /// because it reduces round-trips for DDL scripts and multi-statement setup.
1288    ///
1289    /// # Example
1290    ///
1291    /// ```no_run
1292    /// use hyperdb_api::{Connection, CreateMode, Result};
1293    ///
1294    /// fn main() -> Result<()> {
1295    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::DoNotCreate)?;
1296    ///     let total = conn.execute_batch(&[
1297    ///         "CREATE TABLE users (id INT, name TEXT)",
1298    ///         "INSERT INTO users VALUES (1, 'Alice')",
1299    ///         "INSERT INTO users VALUES (2, 'Bob')",
1300    ///     ])?;
1301    ///     println!("Total affected: {}", total);
1302    ///     Ok(())
1303    /// }
1304    /// ```
1305    ///
1306    /// # Errors
1307    ///
1308    /// Returns a wrapped [`Error::Internal`] on the first statement that fails;
1309    /// its `source` is the original [`Error::Server`] from
1310    /// [`execute_command`](Self::execute_command). The error message
1311    /// includes the failing statement's ordinal and an 80-character preview
1312    /// of its SQL.
1313    pub fn execute_batch(&self, statements: &[&str]) -> Result<u64> {
1314        let mut total = 0u64;
1315        for (i, stmt) in statements.iter().enumerate() {
1316            if !stmt.trim().is_empty() {
1317                total += self.execute_command(stmt).map_err(|e| {
1318                    let preview: String = stmt.chars().take(80).collect();
1319                    Error::internal(format!(
1320                        "execute_batch failed at statement {} of {}: {}: {}",
1321                        i + 1,
1322                        statements.len(),
1323                        preview,
1324                        e,
1325                    ))
1326                })?;
1327            }
1328        }
1329        Ok(total)
1330    }
1331
1332    /// Returns the attached database path, if any.
1333    pub fn database(&self) -> Option<&str> {
1334        self.database.as_deref()
1335    }
1336
1337    /// Creates a new database file.
1338    ///
1339    /// # Example
1340    ///
1341    /// ```no_run
1342    /// use hyperdb_api::{Connection, Result};
1343    ///
1344    /// fn main() -> Result<()> {
1345    ///     let conn = Connection::without_database("localhost:7483")?;
1346    ///     conn.create_database("new_database.hyper")?;
1347    ///     Ok(())
1348    /// }
1349    /// ```
1350    ///
1351    /// # Errors
1352    ///
1353    /// Returns [`Error::Server`] if the server rejects the
1354    /// `CREATE DATABASE IF NOT EXISTS` statement (e.g. the path is not
1355    /// writable on the server).
1356    pub fn create_database(&self, path: &str) -> Result<()> {
1357        let sql = format!("CREATE DATABASE IF NOT EXISTS {}", escape_sql_path(path));
1358        self.execute_command(&sql)?;
1359        Ok(())
1360    }
1361
1362    /// Drops (deletes) a database file.
1363    ///
1364    /// # Example
1365    ///
1366    /// ```no_run
1367    /// use hyperdb_api::{Connection, Result};
1368    ///
1369    /// fn main() -> Result<()> {
1370    ///     let conn = Connection::without_database("localhost:7483")?;
1371    ///     conn.drop_database("old_database.hyper")?;
1372    ///     Ok(())
1373    /// }
1374    /// ```
1375    ///
1376    /// # Errors
1377    ///
1378    /// Returns [`Error::Server`] if the server rejects the
1379    /// `DROP DATABASE IF EXISTS` statement (e.g. the database is still
1380    /// attached or permissions deny deletion).
1381    pub fn drop_database(&self, path: &str) -> Result<()> {
1382        let sql = format!("DROP DATABASE IF EXISTS {}", escape_sql_path(path));
1383        self.execute_command(&sql)?;
1384        Ok(())
1385    }
1386
1387    /// Attaches a database file to the connection.
1388    ///
1389    /// Once attached, the database can be queried and modified.
1390    /// The database is identified by its alias (or by its path if no alias is provided).
1391    ///
1392    /// # Arguments
1393    ///
1394    /// * `path` - The path to the database file to attach.
1395    /// * `alias` - Optional alias for the database. If `None`, the database is
1396    ///   attached without an explicit alias (typically using its filename).
1397    ///
1398    /// # Errors
1399    ///
1400    /// Returns an error if the database file doesn't exist or if attachment fails.
1401    ///
1402    /// # Example
1403    ///
1404    /// ```no_run
1405    /// use hyperdb_api::{Connection, Result};
1406    ///
1407    /// fn main() -> Result<()> {
1408    ///     let conn = Connection::without_database("localhost:7483")?;
1409    ///
1410    ///     // Attach with an alias
1411    ///     conn.attach_database("data.hyper", Some("mydata"))?;
1412    ///
1413    ///     // Attach without an alias
1414    ///     conn.attach_database("other.hyper", None)?;
1415    ///     Ok(())
1416    /// }
1417    /// ```
1418    pub fn attach_database(&self, path: &str, alias: Option<&str>) -> Result<()> {
1419        let sql = if let Some(alias) = alias {
1420            format!(
1421                "ATTACH DATABASE {} AS {}",
1422                escape_sql_path(path),
1423                escape_sql_path(alias)
1424            )
1425        } else {
1426            format!("ATTACH DATABASE {}", escape_sql_path(path))
1427        };
1428        self.execute_command(&sql)?;
1429        Ok(())
1430    }
1431
1432    /// Detaches a database from this connection.
1433    ///
1434    /// After detaching, the database file is released and can be accessed
1435    /// externally (e.g., copied, moved, etc.). All pending updates are
1436    /// written to disk before detaching.
1437    ///
1438    /// # Arguments
1439    ///
1440    /// * `alias` - The alias of the database to detach.
1441    ///
1442    /// # Errors
1443    ///
1444    /// Returns an error if the database is not attached or if detachment fails.
1445    ///
1446    /// # Example
1447    ///
1448    /// ```no_run
1449    /// use hyperdb_api::{Connection, Result};
1450    ///
1451    /// fn main() -> Result<()> {
1452    ///     let conn = Connection::without_database("localhost:7483")?;
1453    ///     conn.attach_database("data.hyper", Some("mydata"))?;
1454    ///     // ... work with the database ...
1455    ///     conn.detach_database("mydata")?;
1456    ///     Ok(())
1457    /// }
1458    /// ```
1459    pub fn detach_database(&self, alias: &str) -> Result<()> {
1460        let sql = format!("DETACH DATABASE {}", escape_sql_path(alias));
1461        self.execute_command(&sql)?;
1462        Ok(())
1463    }
1464
1465    /// Detaches all databases from this connection.
1466    ///
1467    /// This is useful for cleanup before closing a connection or when
1468    /// you need to release all database files.
1469    ///
1470    /// # Errors
1471    ///
1472    /// Returns [`Error::Server`] if the server rejects the
1473    /// `DETACH ALL DATABASES` statement (e.g. a database is still in use by
1474    /// another session).
1475    pub fn detach_all_databases(&self) -> Result<()> {
1476        self.execute_command("DETACH ALL DATABASES")?;
1477        Ok(())
1478    }
1479
1480    /// Creates a schema in the database.
1481    ///
1482    /// # Errors
1483    ///
1484    /// - Returns an error if `schema_name` cannot be converted into a
1485    ///   [`SchemaName`](crate::SchemaName) (invalid identifier).
1486    /// - Returns [`Error::Server`] if the server rejects the
1487    ///   `CREATE SCHEMA` statement (e.g. the schema already exists).
1488    pub fn create_schema<T>(&self, schema_name: T) -> Result<()>
1489    where
1490        T: TryInto<crate::SchemaName>,
1491        crate::Error: From<T::Error>,
1492    {
1493        crate::catalog::Catalog::new(self).create_schema(schema_name)
1494    }
1495
1496    /// Checks whether a schema exists.
1497    ///
1498    /// # Arguments
1499    ///
1500    /// * `schema` - The schema name (can include database qualifier).
1501    ///
1502    /// # Example
1503    ///
1504    /// ```no_run
1505    /// use hyperdb_api::{Connection, Result};
1506    ///
1507    /// fn main() -> Result<()> {
1508    ///     let conn = Connection::without_database("localhost:7483")?;
1509    ///     if conn.has_schema("public")? {
1510    ///         println!("Schema 'public' exists");
1511    ///     }
1512    ///     Ok(())
1513    /// }
1514    /// ```
1515    ///
1516    /// # Errors
1517    ///
1518    /// - Returns an error if `schema` cannot be converted into a
1519    ///   [`SchemaName`](crate::SchemaName).
1520    /// - Returns [`Error::Server`] if the catalog lookup query fails.
1521    pub fn has_schema<T>(&self, schema: T) -> Result<bool>
1522    where
1523        T: TryInto<crate::SchemaName>,
1524        crate::Error: From<T::Error>,
1525    {
1526        use crate::catalog::Catalog;
1527        Catalog::new(self).has_schema(schema)
1528    }
1529
1530    /// Checks whether a table exists.
1531    ///
1532    /// # Arguments
1533    ///
1534    /// * `table_name` - The table name (can include database and schema qualifiers).
1535    ///
1536    /// # Example
1537    ///
1538    /// ```no_run
1539    /// use hyperdb_api::{Connection, Result};
1540    ///
1541    /// fn main() -> Result<()> {
1542    ///     let conn = Connection::without_database("localhost:7483")?;
1543    ///     if conn.has_table("public.users")? {
1544    ///         println!("Table 'users' exists");
1545    ///     }
1546    ///     Ok(())
1547    /// }
1548    /// ```
1549    ///
1550    /// # Errors
1551    ///
1552    /// - Returns an error if `table_name` cannot be converted into a
1553    ///   [`TableName`](crate::TableName).
1554    /// - Returns [`Error::Server`] if the catalog lookup query fails.
1555    pub fn has_table<T>(&self, table_name: T) -> Result<bool>
1556    where
1557        T: TryInto<crate::TableName>,
1558        crate::Error: From<T::Error>,
1559    {
1560        use crate::catalog::Catalog;
1561        Catalog::new(self).has_table(table_name)
1562    }
1563
1564    /// Returns the server version as a parsed struct.
1565    ///
1566    /// Returns `None` if the version cannot be determined (e.g., gRPC connection).
1567    ///
1568    /// # Example
1569    ///
1570    /// ```no_run
1571    /// use hyperdb_api::{Connection, CreateMode, HyperProcess, ServerVersion, Result};
1572    ///
1573    /// fn main() -> Result<()> {
1574    ///     let hyper = HyperProcess::new(None, None)?;
1575    ///     let conn = Connection::new(&hyper, "test.hyper", CreateMode::CreateIfNotExists)?;
1576    ///     if let Some(version) = conn.server_version() {
1577    ///         println!("Hyper {}", version);
1578    ///         if version >= ServerVersion::new(0, 1, 0) {
1579    ///             println!("Has feature X");
1580    ///         }
1581    ///     }
1582    ///     Ok(())
1583    /// }
1584    /// ```
1585    pub fn server_version(&self) -> Option<crate::ServerVersion> {
1586        let version_str = self.parameter_status("server_version")?;
1587        crate::ServerVersion::parse(&version_str)
1588    }
1589
1590    /// Copies a database file to a new path.
1591    ///
1592    /// The source database must be attached to this connection.
1593    ///
1594    /// # Example
1595    ///
1596    /// ```no_run
1597    /// use hyperdb_api::{Connection, CreateMode, HyperProcess, Result};
1598    ///
1599    /// fn main() -> Result<()> {
1600    ///     let hyper = HyperProcess::new(None, None)?;
1601    ///     let conn = Connection::new(&hyper, "source.hyper", CreateMode::DoNotCreate)?;
1602    ///     conn.copy_database("source.hyper", "backup.hyper")?;
1603    ///     Ok(())
1604    /// }
1605    /// ```
1606    ///
1607    /// # Errors
1608    ///
1609    /// Returns [`Error::Server`] if the server rejects the
1610    /// `COPY DATABASE` statement — e.g. the source is not attached, the
1611    /// destination path is not writable, or it already exists.
1612    pub fn copy_database(&self, source: &str, destination: &str) -> Result<()> {
1613        let sql = format!(
1614            "COPY DATABASE {} TO {}",
1615            escape_sql_path(source),
1616            escape_sql_path(destination)
1617        );
1618        self.execute_command(&sql)?;
1619        Ok(())
1620    }
1621
1622    /// Executes EXPLAIN on a query and returns the plan as a string.
1623    ///
1624    /// # Example
1625    ///
1626    /// ```no_run
1627    /// use hyperdb_api::{Connection, CreateMode, Result};
1628    ///
1629    /// fn main() -> Result<()> {
1630    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::DoNotCreate)?;
1631    ///     let plan = conn.explain("SELECT * FROM users WHERE id = 1")?;
1632    ///     println!("{}", plan);
1633    ///     Ok(())
1634    /// }
1635    /// ```
1636    ///
1637    /// # Errors
1638    ///
1639    /// Returns [`Error::Server`] if `EXPLAIN <query>` fails to parse or
1640    /// plan, or if the streamed result cannot be consumed.
1641    pub fn explain(&self, query: &str) -> Result<String> {
1642        let explain_sql = format!("EXPLAIN {query}");
1643        let result = self.execute_query(&explain_sql)?;
1644        let mut lines = Vec::new();
1645        for row in result.rows() {
1646            let row = row?;
1647            if let Some(line) = row.get::<String>(0) {
1648                lines.push(line);
1649            }
1650        }
1651        Ok(lines.join("\n"))
1652    }
1653
1654    /// Executes EXPLAIN ANALYZE on a query and returns the plan with timing info.
1655    ///
1656    /// **Note:** This actually executes the query to collect timing information.
1657    ///
1658    /// # Errors
1659    ///
1660    /// Returns [`Error::Server`] if `EXPLAIN ANALYZE <query>` fails — this
1661    /// includes any runtime error raised by actually executing `query`.
1662    pub fn explain_analyze(&self, query: &str) -> Result<String> {
1663        let explain_sql = format!("EXPLAIN ANALYZE {query}");
1664        let result = self.execute_query(&explain_sql)?;
1665        let mut lines = Vec::new();
1666        for row in result.rows() {
1667            let row = row?;
1668            if let Some(line) = row.get::<String>(0) {
1669                lines.push(line);
1670            }
1671        }
1672        Ok(lines.join("\n"))
1673    }
1674
1675    /// Returns a reference to the underlying TCP client.
1676    ///
1677    /// # Panics
1678    ///
1679    /// This method returns `None` if the connection is using gRPC transport.
1680    pub fn tcp_client(&self) -> Option<&Client> {
1681        match &self.transport {
1682            Transport::Tcp(tcp) => Some(&tcp.client),
1683            Transport::Grpc(_) => None,
1684        }
1685    }
1686
1687    /// Crate-internal accessor for the transport. Used by
1688    /// [`PreparedStatement`](crate::PreparedStatement) to reach the
1689    /// underlying `hyperdb_api_core::client::Client`.
1690    pub(crate) fn transport(&self) -> &Transport {
1691        &self.transport
1692    }
1693
1694    /// Prepares a SQL statement with automatic parameter type inference.
1695    ///
1696    /// The returned [`PreparedStatement`](crate::PreparedStatement) can
1697    /// be executed many times with different parameter values; the
1698    /// server caches the parsed plan. This is the preferred way to
1699    /// execute a statement repeatedly inside a loop.
1700    ///
1701    /// For explicit parameter types (necessary when `$N` placeholders
1702    /// would otherwise be ambiguous), use
1703    /// [`prepare_typed`](Self::prepare_typed).
1704    ///
1705    /// # Example
1706    ///
1707    /// ```no_run
1708    /// # use hyperdb_api::{Connection, CreateMode, Result};
1709    /// # fn example(conn: &Connection) -> Result<()> {
1710    /// let stmt = conn.prepare("SELECT name FROM users WHERE id = $1")?;
1711    /// for id in [1_i32, 2, 3] {
1712    ///     let name: String = stmt.fetch_scalar(&[&id])?;
1713    ///     println!("{id}: {name}");
1714    /// }
1715    /// # Ok(())
1716    /// # }
1717    /// ```
1718    ///
1719    /// # Errors
1720    ///
1721    /// See [`prepare_typed`](Self::prepare_typed) — this method delegates
1722    /// to it with an empty OID list.
1723    pub fn prepare(&self, query: &str) -> Result<crate::PreparedStatement<'_>> {
1724        self.prepare_typed(query, &[])
1725    }
1726
1727    /// Prepares a SQL statement with explicit parameter type OIDs.
1728    ///
1729    /// Use this when the server cannot infer parameter types from the
1730    /// SQL alone (e.g. a bare `$1` in a `WHERE v > $1` clause with no
1731    /// other context). Constants for common types live in
1732    /// [`hyperdb_api_core::types::oids`].
1733    ///
1734    /// # Errors
1735    ///
1736    /// - Returns [`Error::FeatureNotSupported`] if the connection is using gRPC transport
1737    ///   (prepared statements are TCP-only).
1738    /// - Returns [`Error::Server`] if the server rejects the `Parse`
1739    ///   message, e.g. SQL syntax error or unknown OID.
1740    /// - Returns [`Error::Io`] on transport-level I/O failures.
1741    pub fn prepare_typed(
1742        &self,
1743        query: &str,
1744        param_types: &[crate::Oid],
1745    ) -> Result<crate::PreparedStatement<'_>> {
1746        let client = match &self.transport {
1747            Transport::Tcp(tcp) => &tcp.client,
1748            Transport::Grpc(_) => {
1749                return Err(Error::feature_not_supported(
1750                    "prepared statements are not supported over gRPC transport",
1751                ));
1752            }
1753        };
1754        let inner = client.prepare_typed(query, param_types)?;
1755        crate::PreparedStatement::new(self, inner)
1756    }
1757
1758    /// Returns true if the connection is alive (passive check).
1759    ///
1760    /// This is a lightweight check that does not send any data to the server.
1761    /// For an active health check, use [`ping`](Self::ping).
1762    pub fn is_alive(&self) -> bool {
1763        match &self.transport {
1764            Transport::Tcp(tcp) => tcp.client.is_alive(),
1765            Transport::Grpc(_) => true, // gRPC connections are stateless
1766        }
1767    }
1768
1769    /// Actively checks that the connection is healthy by executing a trivial query.
1770    ///
1771    /// Unlike [`is_alive`](Self::is_alive) which only checks local state,
1772    /// this method sends `SELECT 1` to the server and verifies a response.
1773    ///
1774    /// # Example
1775    ///
1776    /// ```no_run
1777    /// # use hyperdb_api::{Connection, CreateMode, Result};
1778    /// # fn example(conn: &Connection) -> Result<()> {
1779    /// if conn.ping().is_ok() {
1780    ///     println!("Connection is healthy");
1781    /// }
1782    /// # Ok(())
1783    /// # }
1784    /// ```
1785    ///
1786    /// # Errors
1787    ///
1788    /// Returns [`Error::Server`] or [`Error::Io`] if the `SELECT 1`
1789    /// round-trip fails — i.e. the connection is no longer usable.
1790    pub fn ping(&self) -> Result<()> {
1791        self.execute_command("SELECT 1")?;
1792        Ok(())
1793    }
1794
1795    /// Returns the process ID of the backend server connection.
1796    ///
1797    /// Returns 0 for gRPC connections (not applicable).
1798    pub fn process_id(&self) -> i32 {
1799        match &self.transport {
1800            Transport::Tcp(tcp) => tcp.client.process_id(),
1801            Transport::Grpc(_) => 0,
1802        }
1803    }
1804
1805    /// Returns the secret key for the backend server connection.
1806    ///
1807    /// This is used for cancellation requests.
1808    /// Returns 0 for gRPC connections (not applicable).
1809    pub fn secret_key(&self) -> i32 {
1810        match &self.transport {
1811            Transport::Tcp(tcp) => tcp.client.secret_key(),
1812            Transport::Grpc(_) => 0,
1813        }
1814    }
1815
1816    /// Returns a server parameter value by name.
1817    ///
1818    /// Server parameters are sent by the server during connection startup.
1819    /// Common parameters include:
1820    /// - `server_version` - The server version string
1821    /// - `server_encoding` - The server's character encoding
1822    /// - `client_encoding` - The client's character encoding
1823    /// - `DateStyle` - Date display format
1824    /// - `TimeZone` - Server timezone
1825    /// - `session_identifier` - Session ID for connection migration (if routing enabled)
1826    ///
1827    /// Returns `None` if the parameter is not known.
1828    ///
1829    /// # Example
1830    ///
1831    /// ```no_run
1832    /// use hyperdb_api::{Connection, CreateMode, HyperProcess, Result};
1833    ///
1834    /// fn main() -> Result<()> {
1835    ///     let hyper = HyperProcess::new(None, None)?;
1836    ///     let conn = Connection::new(&hyper, "test.hyper", CreateMode::CreateIfNotExists)?;
1837    ///
1838    ///     if let Some(version) = conn.parameter_status("server_version") {
1839    ///         println!("Connected to Hyper version: {}", version);
1840    ///     }
1841    ///     Ok(())
1842    /// }
1843    /// ```
1844    pub fn parameter_status(&self, name: &str) -> Option<String> {
1845        match &self.transport {
1846            Transport::Tcp(tcp) => tcp.client.parameter_status(name),
1847            Transport::Grpc(_) => None, // gRPC doesn't have server parameters
1848        }
1849    }
1850
1851    /// Sets the notice receiver for this connection.
1852    ///
1853    /// Server notices and warnings are passed to this callback instead of being
1854    /// logged. Pass `None` to restore default logging behavior.
1855    pub fn set_notice_receiver(
1856        &mut self,
1857        receiver: Option<hyperdb_api_core::client::NoticeReceiver>,
1858    ) {
1859        match &mut self.transport {
1860            Transport::Tcp(tcp) => tcp.client.set_notice_receiver(receiver),
1861            Transport::Grpc(_) => {} // gRPC doesn't support notice receivers
1862        }
1863    }
1864
1865    /// Cancels the currently executing query (thread-safe).
1866    ///
1867    /// # Errors
1868    ///
1869    /// - Returns [`Error::FeatureNotSupported`] on gRPC connections — cancellation is not
1870    ///   yet implemented for gRPC transport.
1871    /// - Returns [`Error::Connection`] or [`Error::Io`] if the separate
1872    ///   cancel-request connection to the server fails.
1873    pub fn cancel(&self) -> Result<()> {
1874        match &self.transport {
1875            Transport::Tcp(tcp) => tcp.client.cancel().map_err(Error::from),
1876            Transport::Grpc(_) => Err(Error::feature_not_supported(
1877                "Query cancellation is not yet supported for gRPC connections.",
1878            )),
1879        }
1880    }
1881
1882    /// Closes the connection, detaching all databases first.
1883    ///
1884    /// # Errors
1885    ///
1886    /// - Returns [`Error::Internal`] wrapping the underlying close failure
1887    ///   (its `source` is the transport error) if the client cannot be
1888    ///   shut down cleanly.
1889    /// - Returns [`Error::Internal`] wrapping the detach failure if the
1890    ///   attached database could not be detached but close itself
1891    ///   succeeded.
1892    pub fn close(self) -> Result<()> {
1893        // Detach the attached database to ensure files are flushed and released.
1894        // Always attempt close, even if detach fails.
1895        let detach_err = if let Some(ref db_path) = self.database {
1896            let db_alias = std::path::Path::new(db_path)
1897                .file_stem()
1898                .and_then(|s| s.to_str())
1899                .unwrap_or("db");
1900            self.execute_command(&format!("DETACH DATABASE {}", escape_sql_path(db_alias)))
1901                .err()
1902        } else {
1903            None
1904        };
1905
1906        // Always attempt to close the client to release the connection.
1907        let close_result = match self.transport {
1908            Transport::Tcp(tcp) => tcp.client.close(),
1909            Transport::Grpc(_) => Ok(()), // gRPC connections are stateless
1910        };
1911
1912        if let Err(e) = close_result {
1913            return Err(Error::internal(format!("Failed to close connection: {e}")));
1914        }
1915
1916        if let Some(e) = detach_err {
1917            // Detach failed but close succeeded; surface the detach error.
1918            return Err(Error::internal(format!(
1919                "Failed to detach database during close: {e}"
1920            )));
1921        }
1922
1923        Ok(())
1924    }
1925
1926    /// Unloads the database from memory while keeping the connection active.
1927    ///
1928    /// This executes the `UNLOAD DATABASE` command, which releases the database
1929    /// from memory but keeps the session and connection open. The database can
1930    /// be accessed again by subsequent queries that will automatically reload it.
1931    ///
1932    /// This is useful for releasing memory locks when switching between databases
1933    /// or when working with multiple database files.
1934    ///
1935    /// # Example
1936    ///
1937    /// ```no_run
1938    /// use hyperdb_api::{Connection, CreateMode, HyperProcess, Result};
1939    ///
1940    /// fn main() -> Result<()> {
1941    ///     let hyper = HyperProcess::new(None, None)?;
1942    ///     let conn = Connection::new(&hyper, "test.hyper", CreateMode::Create)?;
1943    ///     
1944    ///     // Do some work with the database
1945    ///     conn.execute_command("CREATE TABLE test (id INT)")?;
1946    ///     
1947    ///     // Unload from memory (but keep connection)
1948    ///     conn.unload_database()?;
1949    ///     
1950    ///     // Database can still be accessed (will be reloaded automatically)
1951    ///     let count: i64 = conn.fetch_scalar("SELECT COUNT(*) FROM test")?;
1952    ///     println!("Count: {}", count);
1953    ///     
1954    ///     Ok(())
1955    /// }
1956    /// ```
1957    ///
1958    /// # Errors
1959    ///
1960    /// Returns [`Error::Server`] if the server rejects the `UNLOAD DATABASE`
1961    /// command (e.g. the database is still in use by another session).
1962    pub fn unload_database(&self) -> Result<()> {
1963        self.execute_command("UNLOAD DATABASE")?;
1964        Ok(())
1965    }
1966
1967    /// Releases the database completely from the session.
1968    ///
1969    /// This executes the `UNLOAD RELEASE` command, which completely releases
1970    /// the database from the session. After this call, the database cannot
1971    /// be accessed until a new connection is established.
1972    ///
1973    /// This is useful for completely freeing database resources when you're
1974    /// done with a database and want to ensure no locks are held.
1975    ///
1976    /// **Note:** This should only be used when the session has exactly one
1977    /// database attached. Hyper does not support `UNLOAD RELEASE` with
1978    /// multiple databases attached to the same session.
1979    ///
1980    /// # Example
1981    ///
1982    /// ```no_run
1983    /// use hyperdb_api::{Connection, CreateMode, HyperProcess, Result};
1984    ///
1985    /// fn main() -> Result<()> {
1986    ///     let hyper = HyperProcess::new(None, None)?;
1987    ///     let conn = Connection::new(&hyper, "test.hyper", CreateMode::Create)?;
1988    ///     
1989    ///     // Do some work with the database
1990    ///     conn.execute_command("CREATE TABLE test (id INT)")?;
1991    ///     
1992    ///     // Release database completely from session
1993    ///     conn.unload_release()?;
1994    ///     
1995    ///     // Database cannot be accessed after this point without new connection
1996    ///     // conn.execute_command("SELECT * FROM test")?; // This would fail
1997    ///     
1998    ///     Ok(())
1999    /// }
2000    /// ```
2001    ///
2002    /// # Errors
2003    ///
2004    /// Returns [`Error::Server`] if the server rejects `UNLOAD RELEASE`, most
2005    /// commonly because multiple databases are attached to the same session
2006    /// (Hyper only supports `UNLOAD RELEASE` with exactly one attached DB).
2007    pub fn unload_release(&self) -> Result<()> {
2008        self.execute_command("UNLOAD RELEASE")?;
2009        Ok(())
2010    }
2011
2012    // =========================================================================
2013    // Query Statistics
2014    // =========================================================================
2015
2016    /// Enables query statistics collection for this connection.
2017    ///
2018    /// After enabling, each `execute_command()` or `execute_query()` call will
2019    /// capture detailed performance metrics from Hyper. Retrieve them via
2020    /// [`last_query_stats()`](Self::last_query_stats).
2021    ///
2022    /// The provider determines how stats are collected. Use
2023    /// [`LogFileStatsProvider`](crate::LogFileStatsProvider) to parse Hyper's log file (requires local
2024    /// `hyperd.log`), or implement a custom [`QueryStatsProvider`](crate::QueryStatsProvider).
2025    ///
2026    /// # Example
2027    ///
2028    /// ```no_run
2029    /// # use hyperdb_api::{Connection, CreateMode, HyperProcess, Result};
2030    /// # fn main() -> Result<()> {
2031    /// # let hyper = HyperProcess::new(None, None)?;
2032    /// # let mut conn = Connection::new(&hyper, "test.hyper", CreateMode::CreateIfNotExists)?;
2033    /// use hyperdb_api::LogFileStatsProvider;
2034    ///
2035    /// // Auto-detect log path from HyperProcess
2036    /// conn.enable_query_stats(LogFileStatsProvider::from_process(&hyper));
2037    ///
2038    /// // Or specify an explicit log path
2039    /// // conn.enable_query_stats(LogFileStatsProvider::new("/path/to/hyperd.log"));
2040    /// # Ok(())
2041    /// # }
2042    /// ```
2043    pub fn enable_query_stats(&mut self, provider: impl QueryStatsProvider + 'static) {
2044        self.stats_provider = Some(Arc::new(provider));
2045    }
2046
2047    /// Disables query statistics collection.
2048    ///
2049    /// After calling this, `last_query_stats()` will return `None`.
2050    pub fn disable_query_stats(&mut self) {
2051        self.stats_provider = None;
2052        if let Ok(mut guard) = self.pending_stats.lock() {
2053            *guard = None;
2054        }
2055    }
2056
2057    /// Returns the query statistics from the most recent query execution.
2058    ///
2059    /// Stats are resolved **lazily** — the log file is read when this method
2060    /// is called, not when the query executes. This is important for streaming
2061    /// queries (`execute_query`), where Hyper writes the execution stats only
2062    /// after the result set is fully consumed.
2063    ///
2064    /// **Call this after consuming the result set** (e.g., after `collect_rows()`,
2065    /// iterating all chunks, or dropping the `Rowset`).
2066    ///
2067    /// Returns `None` if:
2068    /// - Query stats collection is not enabled
2069    /// - No query has been executed yet
2070    /// - Stats could not be found for the last query (e.g., log entry not matched)
2071    ///
2072    /// # Example
2073    ///
2074    /// ```no_run
2075    /// # use hyperdb_api::{Connection, CreateMode, HyperProcess, Result};
2076    /// # fn main() -> Result<()> {
2077    /// # let hyper = HyperProcess::new(None, None)?;
2078    /// # let mut conn = Connection::new(&hyper, "test.hyper", CreateMode::CreateIfNotExists)?;
2079    /// # use hyperdb_api::LogFileStatsProvider;
2080    /// # conn.enable_query_stats(LogFileStatsProvider::from_process(&hyper));
2081    /// conn.execute_command("CREATE TABLE t (id INT)")?;
2082    ///
2083    /// if let Some(stats) = conn.last_query_stats() {
2084    ///     println!("Total: {}s", stats.elapsed_s);
2085    ///     if let Some(ref pre) = stats.pre_execution {
2086    ///         println!("  Parse: {:?}s", pre.parsing_time_s);
2087    ///         println!("  Compile: {:?}s", pre.compilation_time_s);
2088    ///     }
2089    ///     if let Some(ref exec) = stats.execution {
2090    ///         println!("  Execute: {:?}s", exec.elapsed_s);
2091    ///         println!("  Peak mem: {:?} MB", exec.peak_memory_mb);
2092    ///     }
2093    /// }
2094    /// # Ok(())
2095    /// # }
2096    /// ```
2097    pub fn last_query_stats(&self) -> Option<QueryStats> {
2098        let provider = self.stats_provider.as_ref()?;
2099        let mut guard = self.pending_stats.lock().ok()?;
2100        let (token, sql) = guard.take()?;
2101        provider.after_query(token, &sql)
2102    }
2103
2104    /// Internal: call provider's `before_query` if stats are enabled.
2105    fn stats_before_query(&self, sql: &str) -> Option<Box<dyn Any + Send>> {
2106        self.stats_provider.as_ref().map(|p| p.before_query(sql))
2107    }
2108
2109    /// Internal: store the pending token+sql for lazy resolution.
2110    fn stats_store_pending(&self, token: Option<Box<dyn Any + Send>>, sql: &str) {
2111        if let Some(token) = token
2112            && let Ok(mut guard) = self.pending_stats.lock()
2113        {
2114            *guard = Some((token, sql.to_string()));
2115        }
2116    }
2117}
2118
2119impl Connection {
2120    // =========================================================================
2121    // Transaction Control
2122    // =========================================================================
2123
2124    // -------------------------------------------------------------------
2125    // Raw transaction control (internal)
2126    // -------------------------------------------------------------------
2127    //
2128    // The `*_unguarded` methods below are the canonical implementation of
2129    // session-level transaction control. The RAII guard at
2130    // `crate::Transaction` and any helper that genuinely needs `&self`
2131    // (rather than the guard's `&mut self`) delegate to these.
2132    //
2133    // They are public because a `&self` helper cannot use the guard at all,
2134    // and `hyperdb-mcp`'s engine is exactly that case. They replaced the
2135    // `#[doc(hidden)] #[deprecated]` `begin_transaction`/`commit`/`rollback`
2136    // wrappers, which were removed in 1.0.0.
2137
2138    /// Issues `BEGIN TRANSACTION` without returning a guard.
2139    ///
2140    /// **Prefer [`transaction()`](Self::transaction).** The RAII guard cannot
2141    /// leak a half-open transaction across an error path, and rolls back on
2142    /// drop. Reach for this only when the guard's `&mut self` borrow is
2143    /// impossible — for example inside a helper that holds `&self` and so
2144    /// cannot borrow the connection mutably.
2145    ///
2146    /// Pairing is the caller's responsibility: every call must be matched by
2147    /// [`commit_unguarded`](Self::commit_unguarded) or
2148    /// [`rollback_unguarded`](Self::rollback_unguarded) on **every** path,
2149    /// including panics. Leaving one open wedges the session — subsequent
2150    /// statements fail with "transaction already in progress" on a connection
2151    /// that is otherwise healthy, so reconnect logic will not recover it.
2152    ///
2153    /// # Errors
2154    ///
2155    /// Returns [`Error::Server`] if the server rejects `BEGIN TRANSACTION`
2156    /// (e.g. a transaction is already open on this session).
2157    pub fn begin_transaction_unguarded(&self) -> Result<()> {
2158        self.execute_command("BEGIN TRANSACTION")?;
2159        Ok(())
2160    }
2161
2162    /// Issues `COMMIT` for a transaction opened with
2163    /// [`begin_transaction_unguarded`](Self::begin_transaction_unguarded).
2164    ///
2165    /// **Prefer [`Transaction::commit`](crate::Transaction::commit)** on the
2166    /// guard returned by [`transaction()`](Self::transaction).
2167    ///
2168    /// # Errors
2169    ///
2170    /// Returns [`Error::Server`] if the server rejects `COMMIT`.
2171    pub fn commit_unguarded(&self) -> Result<()> {
2172        self.execute_command("COMMIT")?;
2173        Ok(())
2174    }
2175
2176    /// Issues `ROLLBACK` for a transaction opened with
2177    /// [`begin_transaction_unguarded`](Self::begin_transaction_unguarded).
2178    ///
2179    /// **Prefer [`Transaction::rollback`](crate::Transaction::rollback)** on
2180    /// the guard returned by [`transaction()`](Self::transaction).
2181    ///
2182    /// # Errors
2183    ///
2184    /// Returns [`Error::Server`] if the server rejects `ROLLBACK`.
2185    pub fn rollback_unguarded(&self) -> Result<()> {
2186        self.execute_command("ROLLBACK")?;
2187        Ok(())
2188    }
2189
2190    /// Starts a transaction and returns an RAII guard that auto-rolls back on drop.
2191    ///
2192    /// The returned [`Transaction`](crate::Transaction) exclusively borrows this connection,
2193    /// preventing any other use of the connection while the transaction is active.
2194    /// This is enforced at compile time by Rust's borrow checker. The guard provides
2195    /// `commit()` and `rollback()` methods. If dropped without calling either, the
2196    /// transaction is automatically rolled back.
2197    ///
2198    /// # Example
2199    ///
2200    /// ```no_run
2201    /// # use hyperdb_api::{Connection, CreateMode, Result};
2202    /// # fn main() -> Result<()> {
2203    /// # let mut conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::DoNotCreate)?;
2204    /// let txn = conn.transaction()?;
2205    /// txn.execute_command("INSERT INTO users VALUES (1, 'Alice')")?;
2206    /// txn.commit()?; // or drop `txn` to auto-rollback
2207    /// # Ok(())
2208    /// # }
2209    /// ```
2210    ///
2211    /// # Errors
2212    ///
2213    /// Returns [`Error::Server`] if the server rejects the `BEGIN`
2214    /// statement issued internally by
2215    /// [`Transaction::new`](crate::Transaction).
2216    pub fn transaction(&mut self) -> Result<crate::Transaction<'_>> {
2217        crate::Transaction::new(self)
2218    }
2219}
2220
2221/// Checks if an error indicates an "already exists" condition based on SQLSTATE codes.
2222///
2223/// This function uses `PostgreSQL` SQLSTATE codes to reliably detect duplicate object errors
2224/// regardless of server locale or message formatting. The codes checked are:
2225/// - `42P04`: Database already exists
2226/// - `42710`: Duplicate object
2227/// - `42P06`: Duplicate schema
2228/// - `42P07`: Duplicate table
2229///
2230/// See: <https://www.postgresql.org/docs/current/errcodes-appendix.html>
2231fn is_already_exists_error(err: &Error) -> bool {
2232    err.sqlstate()
2233        .is_some_and(|code| matches!(code, "42P04" | "42710" | "42P06" | "42P07"))
2234}