Skip to main content

Config

Struct Config 

Source
#[non_exhaustive]
pub struct Config {
Show 24 fields pub host: String, pub port: u16, pub database: Option<String>, pub credentials: Credentials, pub tls: TlsConfig, pub application_name: String, pub connect_timeout: Duration, pub command_timeout: Duration, pub packet_size: u16, pub strict_mode: bool, pub trust_server_certificate: bool, pub instance: Option<String>, pub mars: bool, pub encrypt: bool, pub no_tls: bool, pub redirect: RedirectConfig, pub retry: RetryPolicy, pub timeouts: TimeoutConfig, pub tds_version: TdsVersion, pub application_intent: ApplicationIntent, pub workstation_id: Option<String>, pub language: Option<String>, pub multi_subnet_failover: bool, pub send_string_parameters_as_unicode: bool,
}
Expand description

Configuration for connecting to SQL Server.

This struct is marked #[non_exhaustive] to allow adding new fields in future releases without breaking semver. Use Config::default() or Config::from_connection_string() to construct instances.

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§host: String

Server hostname or IP address.

§port: u16

Server port (default: 1433).

§database: Option<String>

Database name.

§credentials: Credentials

Authentication credentials.

§tls: TlsConfig

TLS configuration (only available when tls feature is enabled).

§application_name: String

Application name (shown in SQL Server management tools).

§connect_timeout: Duration

Connection timeout.

§command_timeout: Duration

Command timeout.

§packet_size: u16

TDS packet size.

§strict_mode: bool

Whether to use TDS 8.0 strict mode.

§trust_server_certificate: bool

Whether to trust the server certificate.

§instance: Option<String>

Instance name (for named instances).

§mars: bool

Whether to enable MARS (Multiple Active Result Sets).

§encrypt: bool

Whether to require encryption (TLS). When true, the connection will use TLS even if the server doesn’t require it. When false, encryption is used only if the server requires it.

§no_tls: bool

Disable TLS entirely and connect with plaintext.

⚠️ SECURITY WARNING: This completely disables TLS/SSL encryption. Credentials and data will be transmitted in plaintext. Only use this for development/testing on trusted networks with legacy SQL Server instances that don’t support modern TLS versions.

This option exists for compatibility with legacy SQL Server versions (2008 and earlier) that may only support TLS 1.0/1.1, which modern TLS libraries (like rustls) don’t support for security reasons.

When true:

  • Overrides the encrypt setting
  • Sends ENCRYPT_NOT_SUP in PreLogin
  • No TLS handshake occurs
  • All traffic including login credentials is unencrypted

Do not use in production without understanding the security implications.

§redirect: RedirectConfig

Redirect handling configuration (for Azure SQL).

§retry: RetryPolicy

Retry policy for transient error handling.

§timeouts: TimeoutConfig

Timeout configuration for various connection phases.

§tds_version: TdsVersion

Requested TDS protocol version.

This specifies which TDS protocol version to request during connection. The server may negotiate a lower version if it doesn’t support the requested version.

Supported versions:

  • TdsVersion::V7_3A - SQL Server 2008
  • TdsVersion::V7_3B - SQL Server 2008 R2
  • TdsVersion::V7_4 - SQL Server 2012+ (default)
  • TdsVersion::V8_0 - SQL Server 2022+ strict mode (requires strict_mode = true)

Note: When strict_mode is enabled, this is ignored and TDS 8.0 is used.

§application_intent: ApplicationIntent

Application workload intent for AlwaysOn Availability Group routing.

When set to ApplicationIntent::ReadOnly, SQL Server routes the connection to a readable secondary replica. Sent in LOGIN7 TypeFlags as the READONLY_INTENT bit.

§workstation_id: Option<String>

Client workstation name sent to SQL Server in the LOGIN7 HostName field.

Used for auditing via sys.dm_exec_sessions.host_name. When None, the driver sends the machine hostname (from the COMPUTERNAME or HOSTNAME environment variable). Set via Workstation ID or WSID in connection strings.

§language: Option<String>

Session language for server warning/error messages.

When set, sent in LOGIN7’s Language field. The language name can be up to 128 characters. Set via Language or Current Language in connection strings.

§multi_subnet_failover: bool

Enable MultiSubnetFailover for AlwaysOn Availability Group listeners.

When true, the driver resolves the server hostname to all IP addresses and attempts parallel TCP connections simultaneously. The first successful connection wins and all others are cancelled. This reduces connection time when the AG listener spans multiple subnets.

Set via MultiSubnetFailover=True in connection strings.

Default: false

§send_string_parameters_as_unicode: bool

Whether to send String/&str parameters as NVARCHAR (Unicode).

When true (default), string parameters are sent as NVARCHAR using UTF-16LE encoding. This is safe for all character sets but prevents SQL Server from using index seeks on VARCHAR columns (due to implicit NVARCHAR→VARCHAR conversion).

When false, string parameters are sent as VARCHAR using Windows-1252 encoding. This allows index seeks on VARCHAR columns but may lose data for characters outside the Windows-1252 range.

Set via SendStringParametersAsUnicode=false in connection strings.

Default: true

Implementations§

Source§

impl Config

Source

pub fn new() -> Self

Create a new configuration with default values.

Source

pub fn from_connection_string(conn_str: &str) -> Result<Self, Error>

Parse a connection string into configuration.

Supports ADO.NET-style connection strings with full quoting support:

Server=localhost;Database=mydb;User Id=sa;Password="complex;pass";

Values containing semicolons can be enclosed in double or single quotes per the ADO.NET specification. The tcp: prefix from Azure Portal connection strings is automatically stripped.

Source

pub fn host(self, host: impl Into<String>) -> Self

Set the server host.

Source

pub fn port(self, port: u16) -> Self

Set the server port.

Source

pub fn database(self, database: impl Into<String>) -> Self

Set the database name.

Source

pub fn credentials(self, credentials: Credentials) -> Self

Set the credentials.

Source

pub fn application_name(self, name: impl Into<String>) -> Self

Set the application name.

Source

pub fn connect_timeout(self, timeout: Duration) -> Self

Set the connect timeout.

Source

pub fn trust_server_certificate(self, trust: bool) -> Self

Set trust server certificate option.

Source

pub fn strict_mode(self, enabled: bool) -> Self

Enable TDS 8.0 strict mode.

Source

pub fn tds_version(self, version: TdsVersion) -> Self

Set the TDS protocol version.

This specifies which TDS protocol version to request during connection. The server may negotiate a lower version if it doesn’t support the requested version.

§Examples
use mssql_client::Config;
use tds_protocol::version::TdsVersion;

// Connect to SQL Server 2008
let config = Config::new()
    .host("legacy-server")
    .tds_version(TdsVersion::V7_3A);

// Connect to SQL Server 2008 R2
let config = Config::new()
    .host("legacy-server")
    .tds_version(TdsVersion::V7_3B);

Note: When strict_mode is enabled, this is ignored and TDS 8.0 is used.

Source

pub fn encrypt(self, enabled: bool) -> Self

Enable or disable TLS encryption.

When true (default), the connection will use TLS encryption. When false, encryption is used only if the server requires it.

Warning: Disabling encryption is insecure and should only be used for development/testing on trusted networks.

Source

pub fn no_tls(self, enabled: bool) -> Self

Disable TLS entirely and connect with plaintext (Tiberius-compatible).

⚠️ SECURITY WARNING: This completely disables TLS/SSL encryption. Credentials and all data will be transmitted in plaintext over the network.

§When to use this

This option exists for compatibility with legacy SQL Server versions (2008 and earlier) that may only support TLS 1.0/1.1. Modern TLS libraries like rustls require TLS 1.2 or higher for security reasons, making it impossible to establish encrypted connections to these older servers.

§Security implications

When enabled:

  • Login credentials are sent in plaintext
  • All query data is transmitted without encryption
  • Network traffic can be intercepted and read by attackers

Only use this for development/testing on isolated, trusted networks.

§Example
// Connection string (Tiberius-compatible)
let config = Config::from_connection_string(
    "Server=legacy-server;User Id=sa;Password=secret;Encrypt=no_tls"
)?;

// Builder API
let config = Config::new()
    .host("legacy-server")
    .no_tls(true);
Source

pub fn with_host(self, host: &str) -> Self

Create a new configuration with a different host (for routing).

Source

pub fn with_port(self, port: u16) -> Self

Create a new configuration with a different port (for routing).

Source

pub fn redirect(self, redirect: RedirectConfig) -> Self

Set the redirect handling configuration.

Source

pub fn max_redirects(self, max: u8) -> Self

Set the maximum number of redirect attempts.

Source

pub fn retry(self, retry: RetryPolicy) -> Self

Set the retry policy for transient error handling.

Source

pub fn max_retries(self, max: u32) -> Self

Set the maximum number of retry attempts.

Source

pub fn timeouts(self, timeouts: TimeoutConfig) -> Self

Set the timeout configuration.

Source

pub fn application_intent(self, intent: ApplicationIntent) -> Self

Set the application workload intent for AlwaysOn AG routing.

Source

pub fn workstation_id(self, id: impl Into<String>) -> Self

Set the client workstation name sent to SQL Server in LOGIN7.

This appears in sys.dm_exec_sessions.host_name for auditing. When not set, the driver sends the machine hostname automatically.

Source

pub fn language(self, lang: impl Into<String>) -> Self

Set the session language for server messages.

The language name can be up to 128 characters (e.g., "us_english").

Source

pub fn multi_subnet_failover(self, enabled: bool) -> Self

Enable MultiSubnetFailover for AlwaysOn Availability Group listeners.

When enabled, the driver resolves the server hostname to all IP addresses and races parallel TCP connections. The first successful connection wins.

Source

pub fn send_string_parameters_as_unicode(self, enabled: bool) -> Self

Control whether string parameters are sent as NVARCHAR (Unicode) or VARCHAR.

When false, String/&str parameters are sent as VARCHAR using Windows-1252 encoding, which allows SQL Server to use index seeks on VARCHAR columns.

Default: true (NVARCHAR)

Trait Implementations§

Source§

impl Clone for Config

Source§

fn clone(&self) -> Config

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Config

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for Config

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

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
Source§

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

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

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

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

Performs the conversion.
Source§

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

Source§

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

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

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