Skip to main content

hyperdb_api/
lib.rs

1// Copyright (c) 2026, Salesforce, Inc. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Pure Rust API for Hyper database.
5//!
6//! This crate provides a safe, idiomatic Rust interface for working with
7//! Hyper database files (.hyper). It is a pure-Rust implementation using
8//! the `PostgreSQL` wire protocol with Hyper-specific extensions.
9//!
10//! # Architecture
11//!
12//! This is a layered API built from four crates:
13//! - `hyper-types` — Type definitions with `LittleEndian` encoding
14//! - `hyper-protocol` — Wire protocol with `HyperBinary` COPY support
15//! - `hyper-client` — Sync/async TCP and gRPC clients
16//! - `hyperdb-api` — High-level API (this crate)
17//!
18//! Optional companion crates:
19//! - `sea-query-hyperdb` — `HyperDB` SQL dialect backend for `sea-query`
20//! - `hyperdb-api-salesforce` — Salesforce Data Cloud OAuth authentication
21//! - `hyperdb-api-derive` — Proc-macro `#[derive(FromRow)]` (re-exported by this crate)
22//!
23//! # Quick Start
24//!
25//! ```no_run
26//! use hyperdb_api::{HyperProcess, Connection, CreateMode, Result};
27//!
28//! fn main() -> Result<()> {
29//!     let hyper = HyperProcess::new(None, None)?;
30//!     let conn = Connection::new(&hyper, "example.hyper", CreateMode::CreateIfNotExists)?;
31//!
32//!     conn.execute_command("CREATE TABLE test (id INT, name TEXT)")?;
33//!     conn.execute_command("INSERT INTO test VALUES (1, 'Hello')")?;
34//!
35//!     let mut result = conn.execute_query("SELECT * FROM test")?;
36//!     while let Some(chunk) = result.next_chunk()? {
37//!         for row in &chunk {
38//!             let id: Option<i32> = row.get(0);
39//!             let name: Option<String> = row.get(1);
40//!             println!("id: {:?}, name: {:?}", id, name);
41//!         }
42//!     }
43//!     Ok(())
44//! }
45//! ```
46//!
47//! # Lifetime Safety
48//!
49//! The API uses lifetime annotations to provide compile-time guarantees that
50//! resources are used correctly. All dependent types ([`Inserter`],
51//! [`Catalog`], [`Rowset`], [`Transaction`]) carry a `'conn` lifetime
52//! parameter tying them to the [`Connection`] they borrow:
53//!
54//! ```text
55//! Connection (owns underlying client)
56//! ├── Inserter<'conn>
57//! │   └── CopyInWriter<'conn>
58//! ├── Catalog<'conn>
59//! ├── KvStore<'conn>
60//! ├── Rowset<'conn>
61//! └── Transaction<'conn>
62//! ```
63//!
64//! This is a **simple hierarchical design**, not a complex lifetime web:
65//! - **Single root owner**: `Connection` owns the underlying client
66//! - **Simple borrows**: All dependent types borrow `&'conn Connection`
67//! - **No circular references**: `Inserter` doesn't reference `Catalog`, etc.
68//! - **Single lifetime parameter**: Just one `'conn` — no multi-lifetime bounds
69//!
70//! The Rust borrow checker enforces that you cannot drop or move a `Connection`
71//! while any dependent type holds a reference to it:
72//!
73//! ```compile_fail
74//! # use hyperdb_api::{Connection, Inserter, CreateMode};
75//! # fn example() -> hyperdb_api::Result<()> {
76//! let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::CreateIfNotExists)?;
77//! let inserter = Inserter::new(&conn, /* ... */)?;
78//! drop(conn);  // ERROR: cannot move `conn` because it is borrowed by `inserter`
79//! # Ok(())
80//! # }
81//! ```
82//!
83//! The same guarantee holds for a [`KvStore`], which borrows its `Connection`
84//! for the handle's lifetime:
85//!
86//! ```compile_fail
87//! # use hyperdb_api::{Connection, CreateMode};
88//! # fn example() -> hyperdb_api::Result<()> {
89//! let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::CreateIfNotExists)?;
90//! let kv = conn.kv_store("s")?;
91//! drop(conn);  // ERROR: cannot move `conn` because it is borrowed by `kv`
92//! let _ = kv.get("k")?;
93//! # Ok(())
94//! # }
95//! ```
96//!
97//! The `execute(self)` method on [`Inserter`] takes ownership (`self`), which
98//! automatically ends the borrow when the insert completes — no manual cleanup
99//! needed.
100//!
101//! # Key Types
102//!
103//! - [`Connection`] / [`AsyncConnection`] — Sync and async database connections
104//! - [`HyperProcess`] — Manage a local `hyperd` server process
105//! - [`Inserter`] / [`MappedInserter`] / [`AsyncInserter`] — Bulk row insertion (`HyperBinary` COPY)
106//! - [`ArrowInserter`] / [`AsyncArrowInserter`] — Arrow `RecordBatch` insertion
107//! - [`Catalog`] — Schema/table introspection
108//! - [`TableDefinition`] — Define table schemas
109//! - [`Transaction`] / [`AsyncTransaction`] — RAII transaction guards
110//! - [`KvStore`] / [`AsyncKvStore`] — String-native key-value store over a shared backing table
111//!
112//! # Public Modules
113//!
114//! - [`copy`] — CSV/text export and import via COPY protocol
115//! - [`pool`] — Async connection pooling (deadpool-based)
116//! - [`grpc`] — gRPC transport types for Arrow IPC queries
117//!
118//! # Bulk Data Loading
119//!
120//! Several inserter APIs are available depending on your data format and runtime model:
121//! - [`Inserter`] / [`MappedInserter`] — Sync `HyperBinary` row-by-row
122//! - [`AsyncInserter`] — Async `HyperBinary` row-by-row (mirrors [`Inserter`])
123//! - [`ArrowInserter`] — Sync Arrow IPC (batch or streaming `RecordBatch`)
124//! - [`AsyncArrowInserter`] — Async Arrow IPC
125//! - [`copy`] module — CSV/TSV/delimited text import & export
126//!
127//! # Authentication
128//!
129//! The client supports multiple authentication methods (Trust, Cleartext, MD5, SCRAM-SHA-256):
130//!
131//! ```no_run
132//! use hyperdb_api::{Connection, CreateMode, Result};
133//!
134//! fn main() -> Result<()> {
135//!     let conn = Connection::connect_with_auth(
136//!         "localhost:7483",
137//!         "example.hyper",
138//!         CreateMode::CreateIfNotExists,
139//!         "myuser",
140//!         "mypassword",
141//!     )?;
142//!     Ok(())
143//! }
144//! ```
145
146#![warn(missing_docs, rust_2018_idioms, clippy::all)]
147
148mod arrow_inserter;
149/// Semantic version of this crate, resolved at compile time from
150/// `Cargo.toml`. Used by downstream tools (notably `hyperdb-mcp`) to
151/// surface the library version in their own status output without
152/// duplicating the version string.
153pub const VERSION: &str = env!("CARGO_PKG_VERSION");
154
155mod arrow_reader;
156mod arrow_result;
157mod async_arrow_inserter;
158mod async_connection;
159mod async_connection_builder;
160mod async_inserter;
161mod async_kv_store;
162mod async_prepared;
163mod async_result;
164mod async_transaction;
165mod async_transport;
166mod catalog;
167mod connection;
168mod connection_builder;
169pub mod copy;
170mod data_format;
171mod error;
172mod inserter;
173mod kv_store;
174mod names;
175mod params;
176pub mod pool;
177mod prepared;
178mod process;
179mod query_as;
180mod query_result;
181pub(crate) mod query_stats;
182mod result;
183mod row_accessor;
184mod server_version;
185mod table;
186mod table_definition;
187mod transaction;
188mod transport;
189
190mod grpc_connection;
191#[cfg(kani)]
192mod proofs;
193
194pub use arrow_inserter::ArrowInserter;
195pub use arrow_reader::ArrowReader;
196pub use arrow_result::{
197    parse_arrow_ipc, ArrowChunk, ArrowRow, ArrowRowset, ChunkSource, FromArrowValue,
198};
199pub use async_arrow_inserter::{AsyncArrowInserter, AsyncArrowInserterOwned};
200pub use async_connection::AsyncConnection;
201pub use async_connection_builder::AsyncConnectionBuilder;
202pub use async_inserter::AsyncInserter;
203pub use async_kv_store::AsyncKvStore;
204pub use async_prepared::{AsyncPreparedStatement, AsyncPreparedStatementOwned};
205pub use async_result::AsyncRowset;
206pub use catalog::Catalog;
207pub use connection::{Connection, CreateMode, ScalarValue};
208pub use connection_builder::ConnectionBuilder;
209pub use error::{ColumnErrorKind, Error, Result};
210pub use params::ToSqlParam;
211pub use prepared::PreparedStatement;
212// Re-export Notice for callback registrants. ErrorKind is intentionally
213// NOT re-exported — callers match directly on the flat `Error` enum.
214pub use async_transaction::AsyncTransaction;
215pub use hyperdb_api_core::client::{Notice, NoticeReceiver};
216pub use inserter::{ChunkSender, ColumnMapping, InsertChunk, Inserter, IntoValue, MappedInserter};
217pub use kv_store::KvStore;
218pub use names::{
219    escape_name, escape_sql_path, escape_string_literal, DatabaseName, Name, SchemaName, TableName,
220};
221pub use process::{HyperProcess, ListenMode, Parameters, TransportMode};
222pub use query_stats::{LogFileStatsProvider, QueryStats, QueryStatsProvider};
223pub use result::{FromRow, ResultColumn, ResultSchema, Row, RowIterator, RowValue, Rowset};
224pub use row_accessor::RowAccessor;
225
226// NOTE: proc-macro re-exports (FromRow, Table, query_as!) are intentionally
227// absent from hyperdb-api. Re-exporting them creates a dependency cycle:
228//   hyperdb-api → hyperdb-api-derive → hyperdb-compile-check → hyperdb-api
229// Users add `hyperdb-api-derive` directly with the features they need.
230pub use query_as::{QueryAs, QueryScalar};
231pub use server_version::ServerVersion;
232pub use table::Table;
233pub use table_definition::{ColumnDefinition, Persistence, TableDefinition};
234pub use transaction::Transaction;
235
236// Re-export types from hyperdb-api-core's types layer.
237pub use hyperdb_api_core::types::{
238    Date, Geography, Interval, Nullability, Numeric, OffsetTimestamp, Oid, SqlType, Time,
239    Timestamp, Type,
240};
241
242/// Re-export of `GeoError` from hyperdb-api-core::types.
243pub use hyperdb_api_core::types::GeoError;
244
245/// Re-export of the PostgreSQL OID constants. Access as `hyperdb_api::oids::INT4` etc.
246pub use hyperdb_api_core::types::oids;
247
248// Re-export gRPC types (always available)
249pub mod grpc {
250    //! gRPC transport types for Hyper database access.
251    //!
252    //! This module provides two ways to use gRPC:
253    //!
254    //! 1. **Unified Connection** (recommended): Use `Connection::connect()` with an
255    //!    `https://` or `http://` URL - transport is auto-detected.
256    //!
257    //! 2. **Direct gRPC**: Use `GrpcConnection` or `GrpcConnectionAsync` for
258    //!    explicit gRPC access with full control over transfer modes and async.
259    //!
260    //! # Transfer Modes
261    //!
262    //! - `TransferMode::Sync` - All results in one response (simple, 100s timeout)
263    //! - `TransferMode::Async` - Header only, fetch results via `GetQueryResult`
264    //! - `TransferMode::Adaptive` - First chunk inline, rest streamed (default, recommended)
265
266    // Re-export connection types from grpc_connection module
267    pub use crate::grpc_connection::{GrpcConnection, GrpcConnectionAsync};
268
269    // Re-export types from hyperdb_api_core::client::grpc
270    pub use hyperdb_api_core::client::grpc::{
271        GrpcClient, GrpcClientSync, GrpcConfig, GrpcError, GrpcQueryResult, GrpcResultChunk,
272        TransferMode,
273    };
274}
275
276/// Macro for creating table definitions with a fluent syntax.
277///
278/// This macro simplifies the common pattern of creating table definitions
279/// with multiple columns by providing a more compact syntax.
280///
281/// # Syntax
282///
283/// ```text
284/// table! {
285///     "table_name" {
286///         "column_name": SqlType::type_name(), NULLABLE | NOT_NULL,
287///         // ... more columns
288///     }
289/// }
290/// ```
291///
292/// # Example
293///
294/// ```no_run
295/// # use hyperdb_api::{table, TableDefinition, SqlType, Result};
296/// # fn example() -> Result<()> {
297/// let orders = table! {
298///     "Orders" {
299///         "Address ID": SqlType::small_int(), NOT_NULL,
300///         "Customer ID": SqlType::text(), NOT_NULL,
301///         "Order Date": SqlType::date(), NOT_NULL,
302///         "Order ID": SqlType::text(), NOT_NULL,
303///         "Ship Date": SqlType::date(), NULLABLE,
304///         "Ship Mode": SqlType::text(), NULLABLE,
305///     }
306/// };
307///
308/// // Equivalent to:
309/// let orders_manual = TableDefinition::new("Orders")
310///     .add_required_column("Address ID", SqlType::small_int())
311///     .add_required_column("Customer ID", SqlType::text())
312///     .add_required_column("Order Date", SqlType::date())
313///     .add_required_column("Order ID", SqlType::text())
314///     .add_nullable_column("Ship Date", SqlType::date())
315///     .add_nullable_column("Ship Mode", SqlType::text());
316/// # Ok(())
317/// # }
318/// ```
319#[macro_export]
320macro_rules! table {
321    // Match table with schema.table syntax
322    ($schema:literal.$table:literal {
323        $($col_name:literal: $col_type:expr, $nullability:ident),* $(,)?
324    }) => {{
325        #[allow(unused_mut)]
326        let mut table_def = $crate::TableDefinition::new($table).with_schema($schema);
327        $(
328            table_def = table!(@add_column table_def, $col_name, $col_type, $nullability);
329        )*
330        table_def
331    }};
332
333    // Match simple table name
334    ($table:literal {
335        $($col_name:literal: $col_type:expr, $nullability:ident),* $(,)?
336    }) => {{
337        #[allow(unused_mut)]
338        let mut table_def = $crate::TableDefinition::new($table);
339        $(
340            table_def = table!(@add_column table_def, $col_name, $col_type, $nullability);
341        )*
342        table_def
343    }};
344
345    // Helper to add column based on nullability
346    (@add_column $table_def:expr, $col_name:literal, $col_type:expr, NULLABLE) => {
347        $table_def.add_nullable_column($col_name, $col_type)
348    };
349    (@add_column $table_def:expr, $col_name:literal, $col_type:expr, NOT_NULL) => {
350        $table_def.add_required_column($col_name, $col_type)
351    };
352}