Skip to main content

mssql_client/
lib.rs

1//! # mssql-client
2//!
3//! High-level async SQL Server client with type-state connection management.
4//!
5//! This is the primary public API surface for the rust-mssql-driver project.
6//! It provides a type-safe, ergonomic interface for working with SQL Server
7//! databases.
8//!
9//! ## Features
10//!
11//! - **Type-state pattern**: Compile-time enforcement of connection states
12//! - **Async/await**: Built on Tokio for efficient async I/O
13//! - **Prepared statements**: Automatic caching with LRU eviction
14//! - **Transactions**: Full transaction support with savepoints
15//! - **Azure support**: Automatic routing and failover handling
16//! - **Streaming results**: Memory-efficient processing of large result sets
17//!
18//! ## Type-State Connection Management
19//!
20//! The client uses a compile-time type-state pattern that ensures invalid
21//! operations are caught at compile time rather than runtime:
22//!
23//! ```text
24//! Disconnected -> Ready (via connect())
25//! Ready -> InTransaction (via begin_transaction())
26//! Ready -> Streaming (via query that returns a stream)
27//! InTransaction -> Ready (via commit() or rollback())
28//! ```
29//!
30//! ## Example
31//!
32//! ```rust,ignore
33//! use mssql_client::{Client, Config};
34//!
35//! #[tokio::main]
36//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
37//!     let config = Config::from_connection_string(
38//!         "Server=localhost;Database=test;User Id=sa;Password=Password123;"
39//!     )?;
40//!
41//!     let mut client = Client::connect(config).await?;
42//!
43//!     // Execute a query with parameters
44//!     let rows = client
45//!         .query("SELECT * FROM users WHERE id = @p1", &[&1])
46//!         .await?;
47//!
48//!     for row in rows {
49//!         let name: String = row.get(0)?;
50//!         println!("User: {}", name);
51//!     }
52//!
53//!     // Transactions with savepoint support
54//!     let mut tx = client.begin_transaction().await?;
55//!     tx.execute("INSERT INTO users (name) VALUES (@p1)", &[&"Alice"]).await?;
56//!
57//!     // Create a savepoint for partial rollback
58//!     let sp = tx.savepoint("before_update").await?;
59//!     tx.execute("UPDATE users SET active = 1", &[]).await?;
60//!
61//!     // Rollback to savepoint if needed
62//!     // tx.rollback_to(&sp).await?;
63//!
64//!     tx.commit().await?;
65//!
66//!     Ok(())
67//! }
68//! ```
69
70#![warn(missing_docs)]
71#![deny(unsafe_code)]
72
73// Module dependency graph (acyclic):
74//
75//   client ──→ config, state, error, stream, transaction, statement_cache
76//     ├── connect.rs ──→ config, state, instrumentation, mssql_tls, mssql_codec, tds_protocol
77//     ├── params.rs  ──→ mssql_types, tds_protocol
78//     └── response.rs ──→ error, mssql_codec, tds_protocol
79//   stream ──→ error, row
80//   row ──→ blob, error, mssql_types
81//   config ──→ mssql_auth, mssql_tls, tds_protocol
82//   bulk ──→ error, mssql_types, tds_protocol
83//   cancel ──→ error, mssql_codec, mssql_tls
84//   encryption ──→ mssql_auth, tds_protocol
85//   column_parser ──→ error, mssql_types, tds_protocol
86
87pub mod blob;
88pub mod bulk;
89pub mod cancel;
90pub mod change_tracking;
91pub mod client;
92pub(crate) mod column_parser;
93pub mod config;
94pub mod encryption;
95pub mod error;
96pub mod from_row;
97pub mod instrumentation;
98pub mod query;
99pub mod row;
100pub mod state;
101pub mod statement_cache;
102pub mod stream;
103pub mod to_params;
104pub mod transaction;
105pub mod tvp;
106
107// Re-export commonly used types
108pub use bulk::{BulkColumn, BulkInsert, BulkInsertBuilder, BulkInsertResult, BulkOptions};
109pub use cancel::CancelHandle;
110pub use client::Client;
111pub use config::{Config, RedirectConfig, RetryPolicy, TimeoutConfig};
112pub use error::{Error, SharedIoError};
113
114// Re-export TDS version for configuration
115pub use from_row::{FromRow, MapRows, RowIteratorExt};
116pub use mssql_auth::Credentials;
117pub use tds_protocol::version::TdsVersion;
118
119// Secure credential types (with zeroize feature)
120#[cfg(feature = "zeroize")]
121pub use mssql_auth::{SecretString, SecureCredentials};
122pub use mssql_types::{FromSql, SqlValue, ToSql};
123pub use query::Query;
124pub use row::{Column, Row};
125pub use state::{
126    Connected, ConnectionState, Disconnected, InTransaction, ProtocolState, Ready, Streaming,
127};
128pub use statement_cache::{PreparedStatement, StatementCache, StatementCacheConfig};
129pub use stream::{ExecuteResult, MultiResultStream, OutputParam, QueryStream, ResultSet};
130pub use to_params::{NamedParam, ParamList, ToParams};
131pub use transaction::{IsolationLevel, SavePoint, Transaction};
132pub use tvp::{Tvp, TvpColumn, TvpRow, TvpValue};
133
134// Always Encrypted types
135#[cfg(feature = "always-encrypted")]
136pub use encryption::EncryptionContext;
137pub use encryption::{
138    EncryptionConfig, ParameterCryptoInfo, ParameterEncryptionInfo, ResultSetEncryptionInfo,
139};
140
141// OpenTelemetry instrumentation (available whether or not otel feature is enabled)
142pub use instrumentation::{
143    DatabaseMetrics, OperationTimer, SanitizationConfig, attributes, metric_names, span_names,
144};
145
146// Change Tracking support
147pub use change_tracking::{
148    ChangeMetadata, ChangeOperation, ChangeTracking, ChangeTrackingQuery, SyncVersionStatus,
149};
150
151#[cfg(test)]
152mod auto_trait_tests {
153    //! Compile-time assertions that key async types are Send + Sync.
154    //!
155    //! These tests catch regressions where a type accidentally becomes
156    //! !Send or !Sync due to interior changes (e.g., adding an Rc, Cell,
157    //! or non-Send future). They cost nothing at runtime.
158
159    use super::*;
160
161    fn assert_send<T: Send>() {}
162    fn assert_sync<T: Sync>() {}
163
164    // --- Type-state Client variants ---
165    #[test]
166    fn client_ready_is_send_sync() {
167        assert_send::<Client<Ready>>();
168        assert_sync::<Client<Ready>>();
169    }
170
171    #[test]
172    fn client_in_transaction_is_send_sync() {
173        assert_send::<Client<InTransaction>>();
174        assert_sync::<Client<InTransaction>>();
175    }
176
177    #[test]
178    fn client_disconnected_is_send_sync() {
179        assert_send::<Client<Disconnected>>();
180        assert_sync::<Client<Disconnected>>();
181    }
182
183    #[test]
184    fn client_connected_is_send_sync() {
185        assert_send::<Client<Connected>>();
186        assert_sync::<Client<Connected>>();
187    }
188
189    #[test]
190    fn client_streaming_is_send_sync() {
191        assert_send::<Client<Streaming>>();
192        assert_sync::<Client<Streaming>>();
193    }
194
195    // --- Configuration ---
196    #[test]
197    fn config_is_send_sync() {
198        assert_send::<Config>();
199        assert_sync::<Config>();
200    }
201
202    // --- Streaming types ---
203    #[test]
204    fn query_stream_is_send_sync() {
205        assert_send::<QueryStream<'_>>();
206        assert_sync::<QueryStream<'_>>();
207    }
208
209    #[test]
210    fn multi_result_stream_is_send_sync() {
211        assert_send::<MultiResultStream<'_>>();
212        assert_sync::<MultiResultStream<'_>>();
213    }
214
215    #[test]
216    fn result_set_is_send_sync() {
217        assert_send::<ResultSet>();
218        assert_sync::<ResultSet>();
219    }
220
221    #[test]
222    fn execute_result_is_send_sync() {
223        assert_send::<ExecuteResult>();
224        assert_sync::<ExecuteResult>();
225    }
226
227    // --- Bulk insert types ---
228    #[test]
229    fn bulk_insert_is_send_sync() {
230        assert_send::<BulkInsert>();
231        assert_sync::<BulkInsert>();
232    }
233
234    #[test]
235    fn bulk_insert_builder_is_send_sync() {
236        assert_send::<BulkInsertBuilder>();
237        assert_sync::<BulkInsertBuilder>();
238    }
239
240    #[test]
241    fn bulk_options_is_send_sync() {
242        assert_send::<BulkOptions>();
243        assert_sync::<BulkOptions>();
244    }
245
246    // --- Cancel handle ---
247    #[test]
248    fn cancel_handle_is_send_sync() {
249        assert_send::<CancelHandle>();
250        assert_sync::<CancelHandle>();
251    }
252
253    // --- Row and column types ---
254    #[test]
255    fn row_is_send_sync() {
256        assert_send::<Row>();
257        assert_sync::<Row>();
258    }
259
260    #[test]
261    fn column_is_send_sync() {
262        assert_send::<Column>();
263        assert_sync::<Column>();
264    }
265
266    // --- Statement cache ---
267    #[test]
268    fn statement_cache_is_send_sync() {
269        assert_send::<StatementCache>();
270        assert_sync::<StatementCache>();
271    }
272
273    // --- Error type ---
274    #[test]
275    fn error_is_send_sync() {
276        assert_send::<Error>();
277        assert_sync::<Error>();
278    }
279}