Skip to main content

larust_mssql/
lib.rs

1//! SQL Server support via a hand-written [`larust_repository::Repository`]
2//! implementation, one per model - **not** a `larust_orm::Backend`
3//! variant. `sqlx` has no Microsoft SQL Server driver at all (confirmed by
4//! reading its own source during this crate's design: `sqlx-core`'s only
5//! MSSQL-shaped code is permanently-dead, pre-0.8 scaffolding, and no
6//! `mssql` Cargo feature has ever existed to enable it), so SQL Server
7//! structurally cannot join the `sqlx::Any`/`Backend`/`QueryBuilder`
8//! architecture the way SQLite/MySQL/Postgres do. This crate connects
9//! through [`tiberius`] - a separate, pure-Rust TDS-protocol client with
10//! its own connection type, its own `@P1`/`@P2` parameter syntax, and no
11//! shared code with `larust-orm` at all.
12//!
13//! **Explicit ceiling, stated plainly, not oversold: CRUD only.** No
14//! `#[derive(Model)]` codegen, no relations, no `xr migrate`, no
15//! `QueryBuilder`-style chaining - the same trade-off
16//! `larust_repository::Repository`'s own doc comment already documents
17//! for "a backend `sqlx::Any` structurally cannot reach." This crate owns
18//! only the connection plumbing below; writing an actual `Repository<T>`
19//! implementation for your own model is real, per-model code you write by
20//! hand - there is no generic blanket `impl<T> Repository<T> for
21//! AnyRepository<T>` the way `larust-orm` has for SQL-family backends,
22//! for the same reason that type's own doc comment gives: building
23//! `INSERT`/`UPDATE` text (or here, `tiberius` parameter bindings) from a
24//! struct's fields needs to know those fields, which a function generic
25//! over `T` never does - only code written *for* that specific struct
26//! can. See `tests/widget_repository.rs` for a complete worked example
27//! against a real server, mirroring `larust-repository`'s own
28//! `InMemoryRepository` test in shape, just against `tiberius` instead of
29//! a `HashMap`.
30//!
31//! **The connection is a single, mutex-serialized [`tiberius::Client`],
32//! not a real pool** - `tiberius` has no built-in pooling. This
33//! serializes all SQL Server traffic in a process through one TDS
34//! session, a real and deliberately undisguised limitation for this first
35//! cut, not a glossed-over one. A proper pool (`bb8`/`deadpool` plus a
36//! hand-written `tiberius` adapter) is the natural follow-up if concurrent
37//! load against SQL Server ever becomes a real requirement - explicitly
38//! out of scope here.
39
40use larust_core::AppError;
41use tokio::net::TcpStream;
42use tokio::sync::{Mutex, MutexGuard, OnceCell};
43use tokio_util::compat::{Compat, TokioAsyncWriteCompatExt};
44
45/// Re-exported so a hand-written `Repository<T>` implementation (see this
46/// crate's own doc comment) can build query parameters / read `Row`
47/// values without needing `tiberius` as a second, separately-versioned
48/// direct dependency of its own.
49pub use tiberius;
50
51/// The concrete client type [`client`] hands back, locked. `Compat<
52/// TcpStream>` is `tiberius`'s own transport-agnostic `Client` running
53/// over a plain Tokio TCP stream via the `tokio-util` compatibility shim
54/// (`tiberius` is built against the `futures` `AsyncRead`/`AsyncWrite`
55/// traits, not Tokio's own).
56pub type MssqlClient = tiberius::Client<Compat<TcpStream>>;
57
58static CLIENT: OnceCell<Mutex<MssqlClient>> = OnceCell::const_new();
59
60/// SQL Server connection settings - the same host/port/database/username/
61/// password shape `larust_orm::config::ConnectionConfig` uses for the
62/// SQL-family backends, but deliberately not that type itself: `tiberius`
63/// doesn't take a connection URL the way `sqlx` does, it takes its own
64/// `tiberius::Config` builder, so there's no shared `to_url()`-style
65/// assembly to reuse here.
66#[derive(Debug, Clone)]
67pub struct MssqlConfig {
68    pub host: String,
69    pub port: u16,
70    pub database: String,
71    pub username: String,
72    pub password: String,
73}
74
75/// Connects and stores the client process-wide - same `OnceCell`
76/// singleton idiom `larust_orm::pool()`'s own `OnceLock<AnyPool>` uses.
77/// Call once at startup, before any `Repository<T>` implementation built
78/// on [`client`] runs.
79///
80/// `trust_cert()` is set unconditionally - this targets a local/dev SQL
81/// Server instance the same way this framework's SQLite/MySQL/Postgres
82/// support already does (none of them has a TLS-certificate-verification
83/// story either); a hardened production deployment would need real
84/// certificate handling this first cut doesn't attempt.
85pub async fn connect(config: &MssqlConfig) -> Result<(), AppError> {
86    let mut tiberius_config = tiberius::Config::new();
87    tiberius_config.host(&config.host);
88    tiberius_config.port(config.port);
89    tiberius_config.database(&config.database);
90    tiberius_config.authentication(tiberius::AuthMethod::sql_server(
91        &config.username,
92        &config.password,
93    ));
94    tiberius_config.trust_cert();
95
96    let tcp = TcpStream::connect(tiberius_config.get_addr())
97        .await
98        .map_err(|e| AppError::Internal(Box::new(e)))?;
99    tcp.set_nodelay(true)
100        .map_err(|e| AppError::Internal(Box::new(e)))?;
101
102    let client = tiberius::Client::connect(tiberius_config, tcp.compat_write())
103        .await
104        .map_err(|e| AppError::Internal(Box::new(e)))?;
105
106    CLIENT.set(Mutex::new(client)).map_err(|_| {
107        AppError::Internal(Box::new(std::io::Error::other(
108            "larust_mssql::connect() called more than once",
109        )))
110    })?;
111    Ok(())
112}
113
114/// Returns the process-wide client, locked for exclusive use - released
115/// automatically when the returned guard drops. See this crate's own doc
116/// comment for why this is one mutex-serialized connection, not a pool.
117/// Errors (rather than panics) if [`connect`] hasn't run yet - the same
118/// "a misconfigured startup order is a real possibility" reasoning
119/// `larust_orm::pool()` already documents for its own identical case.
120pub async fn client() -> Result<MutexGuard<'static, MssqlClient>, AppError> {
121    let mutex = CLIENT.get().ok_or_else(|| {
122        AppError::Internal(Box::new(std::io::Error::other(
123            "SQL Server not connected; call larust_mssql::connect() at startup \
124             before any Repository<T> implementation runs",
125        )))
126    })?;
127    Ok(mutex.lock().await)
128}