Client

Struct Client 

Source
pub struct Client<S: ConnectionState> { /* private fields */ }
Expand description

SQL Server client with type-state connection management.

The generic parameter S represents the current connection state, ensuring at compile time that certain operations are only available in appropriate states.

Implementations§

Source§

impl Client<Disconnected>

Source

pub async fn connect(config: Config) -> Result<Client<Ready>>

Connect to SQL Server.

This establishes a connection, performs TLS negotiation (if required), and authenticates with the server.

§Example
let client = Client::connect(config).await?;
Source§

impl Client<Ready>

Source

pub async fn query<'a>( &'a mut self, sql: &str, params: &[&(dyn ToSql + Sync)], ) -> Result<QueryStream<'a>>

Execute a query and return a streaming result set.

Per ADR-007, results are streamed by default for memory efficiency. Use .collect_all() on the stream if you need all rows in memory.

§Example
use futures::StreamExt;

// Streaming (memory-efficient)
let mut stream = client.query("SELECT * FROM users WHERE id = @p1", &[&1]).await?;
while let Some(row) = stream.next().await {
    let row = row?;
    process(&row);
}

// Buffered (loads all into memory)
let rows: Vec<Row> = client
    .query("SELECT * FROM small_table", &[])
    .await?
    .collect_all()
    .await?;
Source

pub async fn query_multiple<'a>( &'a mut self, sql: &str, params: &[&(dyn ToSql + Sync)], ) -> Result<MultiResultStream<'a>>

Execute a batch that may return multiple result sets.

This is useful for stored procedures or SQL batches that contain multiple SELECT statements.

§Example
// Execute a batch with multiple SELECTs
let mut results = client.query_multiple(
    "SELECT 1 AS a; SELECT 2 AS b, 3 AS c;",
    &[]
).await?;

// Process first result set
while let Some(row) = results.next_row().await? {
    println!("Result 1: {:?}", row);
}

// Move to second result set
if results.next_result().await? {
    while let Some(row) = results.next_row().await? {
        println!("Result 2: {:?}", row);
    }
}
Source

pub async fn execute( &mut self, sql: &str, params: &[&(dyn ToSql + Sync)], ) -> Result<u64>

Execute a query that doesn’t return rows.

Returns the number of affected rows.

Source

pub async fn begin_transaction(self) -> Result<Client<InTransaction>>

Begin a transaction.

This transitions the client from Ready to InTransaction state. Per MS-TDS spec, the server returns a transaction descriptor in the BeginTransaction EnvChange token that must be included in subsequent ALL_HEADERS sections.

Source

pub async fn begin_transaction_with_isolation( self, isolation_level: IsolationLevel, ) -> Result<Client<InTransaction>>

Begin a transaction with a specific isolation level.

This transitions the client from Ready to InTransaction state with the specified isolation level.

§Example
use mssql_client::IsolationLevel;

let tx = client.begin_transaction_with_isolation(IsolationLevel::Serializable).await?;
// All operations in this transaction use SERIALIZABLE isolation
tx.commit().await?;
Source

pub async fn simple_query(&mut self, sql: &str) -> Result<()>

Execute a simple query without parameters.

This is useful for DDL statements and simple queries where you don’t need to retrieve the affected row count.

Source

pub async fn close(self) -> Result<()>

Close the connection gracefully.

Source

pub fn database(&self) -> Option<&str>

Get the current database name.

Source

pub fn host(&self) -> &str

Get the server host.

Source

pub fn port(&self) -> u16

Get the server port.

Source§

impl Client<InTransaction>

Source

pub async fn query<'a>( &'a mut self, sql: &str, params: &[&(dyn ToSql + Sync)], ) -> Result<QueryStream<'a>>

Execute a query within the transaction and return a streaming result set.

See Client<Ready>::query for usage examples.

Source

pub async fn execute( &mut self, sql: &str, params: &[&(dyn ToSql + Sync)], ) -> Result<u64>

Execute a statement within the transaction.

Returns the number of affected rows.

Source

pub async fn commit(self) -> Result<Client<Ready>>

Commit the transaction.

This transitions the client back to Ready state.

Source

pub async fn rollback(self) -> Result<Client<Ready>>

Rollback the transaction.

This transitions the client back to Ready state.

Source

pub async fn save_point(&mut self, name: &str) -> Result<SavePoint>

Create a savepoint and return a handle for later rollback.

The returned SavePoint handle contains the validated savepoint name. Use it with rollback_to() to partially undo transaction work.

§Example
let tx = client.begin_transaction().await?;
tx.execute("INSERT INTO orders ...").await?;
let sp = tx.save_point("before_items").await?;
tx.execute("INSERT INTO items ...").await?;
// Oops, rollback just the items
tx.rollback_to(&sp).await?;
tx.commit().await?;
Source

pub async fn rollback_to(&mut self, savepoint: &SavePoint) -> Result<()>

Rollback to a savepoint.

This rolls back all changes made after the savepoint was created, but keeps the transaction active. The savepoint remains valid and can be rolled back to again.

§Example
let sp = tx.save_point("checkpoint").await?;
// ... do some work ...
tx.rollback_to(&sp).await?;  // Undo changes since checkpoint
// Transaction is still active, savepoint is still valid
Source

pub async fn release_savepoint(&mut self, savepoint: SavePoint) -> Result<()>

Release a savepoint (optional cleanup).

Note: SQL Server doesn’t have explicit savepoint release, but this method is provided for API completeness. The savepoint is automatically released when the transaction commits or rolls back.

Trait Implementations§

Source§

impl<S: ConnectionState> Debug for Client<S>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<S> Freeze for Client<S>

§

impl<S> !RefUnwindSafe for Client<S>

§

impl<S> Send for Client<S>
where S: Send,

§

impl<S> Sync for Client<S>
where S: Sync,

§

impl<S> Unpin for Client<S>
where S: Unpin,

§

impl<S> !UnwindSafe for Client<S>

Blanket Implementations§

§

impl<T> Any for T
where T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for T
where T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for T
where T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
§

impl<T, U> Into<U> for T
where U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more