Skip to main content

Config

Struct Config 

Source
pub struct Config { /* private fields */ }
Expand description

The Config struct contains all configuration information required for connecting to the database with a Client. It also provides the server address when connecting to a TcpStream via the get_addr method.

When using an ADO.NET connection string, it can be constructed using the from_ado_string function.

Alternatively, a ConfigBuilder can be used for an ergonomic, chainable construction. Create one via builder, call its setter methods and finalize it with build.

Implementations§

Source§

impl Config

Source

pub fn new() -> Self

Create a new Config with the default settings.

Source

pub fn builder() -> ConfigBuilder

Create a new ConfigBuilder initialized with the default settings.

This provides an ergonomic, chainable alternative to constructing a Config via its individual setter methods.

§Example
let config = Config::builder()
    .host("localhost")
    .port(1433)
    .database("master")
    .authentication(AuthMethod::sql_server("SA", "<password>"))
    .build();

assert_eq!("localhost:1433", config.get_addr());
Source

pub fn host(&mut self, host: impl ToString)

A host or ip address to connect to.

  • Defaults to localhost.
Source

pub fn port(&mut self, port: u16)

The server port.

  • Defaults to 1433.
Source

pub fn database(&mut self, database: impl ToString)

The database to connect to.

  • Defaults to master.
Source

pub fn instance_name(&mut self, name: impl ToString)

The instance name as defined in the SQL Browser. Only available on Windows platforms.

If specified, the port is replaced with the value returned from the browser.

  • Defaults to no name specified.
Source

pub fn application_name(&mut self, name: impl ToString)

Sets the application name to the connection, queryable with the APP_NAME() command.

  • Defaults to tds-driver.
Source

pub fn packet_size(&mut self, size: u32)

Sets the TDS packet size for the connection.

Larger packet sizes can improve bulk insert performance by reducing the number of network round-trips. Valid values are 512 to 32767. The server may negotiate a different size.

  • Defaults to 4096 bytes.
Source

pub fn get_packet_size(&self) -> Option<u32>

Gets the configured packet size, if set.

Source

pub fn encryption(&mut self, encryption: EncryptionLevel)

Set the preferred encryption level.

  • With tls feature, defaults to Required.
  • Without tls feature, defaults to NotSupported.
Source

pub fn trust_cert(&mut self)

If set, the server certificate will not be validated and it is accepted as-is.

On production setting, the certificate should be added to the local key storage (or use trust_cert_ca instead), using this setting is potentially dangerous.

§Panics

Will panic in case trust_cert_ca was called before.

  • Defaults to default, meaning server certificate is validated against system-truststore.
Source

pub fn trust_cert_ca(&mut self, path: impl ToString)

If set, the server certificate will be validated against the given CA certificate in in addition to the system-truststore. Useful when using self-signed certificates on the server without having to disable the trust-chain.

§Panics

Will panic in case trust_cert was called before.

  • Defaults to validating the server certificate is validated against system’s certificate storage.
Source

pub fn hostname_in_certificate(&mut self, hostname: impl ToString)

Sets the hostname that the server certificate is validated against, instead of the value given to host.

This is useful when connecting through an IP address, a tunnel, or a load balancer whose certificate carries a different subject/SAN than the address used to reach it (see issue #340).

  • Defaults to the value of host.
Source

pub fn client_name(&mut self, name: impl ToString)

Sets the client / workstation name reported to the server in the login record (queryable with HOST_NAME()).

  • Defaults to the local workstation id (the machine hostname).
Source

pub fn authentication(&mut self, auth: AuthMethod)

Sets the authentication method.

  • Defaults to None.
Source

pub fn readonly(&mut self, readnoly: bool)

Sets ApplicationIntent readonly.

  • Defaults to false.
Source

pub fn multi_subnet_failover(&mut self, multi_subnet_failover: bool)

Enable multi-subnet failover.

When enabled and the server host name resolves to more than one IP address (for example, an Always On availability group listener spread across subnets), connections are attempted to all resolved addresses in parallel and the first one to succeed is used. This mirrors the ADO.NET MultiSubnetFailover connection-string keyword.

  • Defaults to false.
Source

pub fn get_multi_subnet_failover(&self) -> bool

Returns whether multi-subnet failover is enabled.

Source

pub fn connect_timeout(&self) -> Option<Duration>

How long establishing a connection may take: TCP connect, the SQL Browser lookup, TLS and login. None means no limit.

The crate is runtime-agnostic and owns no timer, so it doesn’t enforce this itself: wrap the TCP connect and Client::connect in your runtime’s timeout.

let config = Config::from_ado_string("server=tcp:db,1433;Connect Timeout=10")?;
let connect = async {
    let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;
    tcp.set_nodelay(true)?;
    Ok::<_, anyhow::Error>(Client::connect(config.clone(), tcp.compat_write()).await?)
};
let client = match config.connect_timeout() {
    Some(limit) => tokio::time::timeout(limit, connect).await??,
    None => connect.await?,
};
  • Defaults to 15 seconds, as in SqlClient. Set from a connection string’s Connect Timeout (ADO.NET, 0 = no limit) or loginTimeout (JDBC, 0 = the 30-second JDBC default).
Source

pub fn set_connect_timeout(&mut self, timeout: Option<Duration>)

Sets the value returned by connect_timeout.

Source

pub fn server_spn(&mut self, spn: impl ToString)

The service principal name integrated authentication asks a ticket for, as given, like SqlClient’s Server SPN. A blank one is ignored.

  • Defaults to MSSQLSvc/<host>:<port>, or MSSQLSvc/<host>:<instance> for a named instance without a port.
Source

pub fn client_certificate( &mut self, cert: impl Into<PathBuf>, key: impl Into<PathBuf>, )

Available on crate features native-tls or rustls or vendored-openssl only.

Supplies a client certificate and private key used to authenticate the client to the server during the TLS handshake (mutual TLS). This is required for TDS 8.0 “strict” connections that use client-certificate authentication (ENCRYPT_CLIENT_CERT), and may also be used with the classic (pre-8.0) TLS handshake when the server requests a client certificate.

Both arguments are paths to files:

  • cert: the client certificate, PEM (.pem/.crt) or DER (.der).
  • key: the matching private key, PEM (.pem/.key) or DER (.der, PKCS#8).

Backend support:

  • rustls: PEM and DER certificate/key files.

  • native-tls: PEM certificate + PEM PKCS#8 key only (DER files are rejected at connect time; use client_certificate_pkcs12 for a bundled DER identity).

  • vendored-openssl (opentls): does not support separate certificate/key files; use client_certificate_pkcs12 instead.

  • Defaults to no client certificate.

Source

pub fn client_certificate_pkcs12( &mut self, path: impl Into<PathBuf>, password: impl Into<String>, )

Available on crate features native-tls or vendored-openssl only.

Supplies a client identity from a PKCS#12 / PFX bundle (certificate, private key and any chain, encrypted with password) used to authenticate the client to the server during the TLS handshake (mutual TLS).

Only supported by the native-tls and vendored-openssl backends; the rustls backend rejects PKCS#12 identities at connect time (supply separate PEM/DER files via client_certificate instead).

  • Defaults to no client certificate.
Source

pub fn get_addr(&self) -> String

Get the host address including port

Source

pub fn from_ado_string(s: &str) -> Result<Self>

Creates a new Config from an ADO.NET connection string.

§Supported parameters

All parameter keys are handled case-insensitive. The last of a key and its synonyms wins, and a key SqlClient doesn’t know is an error.

ParameterAllowed valuesDescription
Data Source, server, addr, address, network address<string>The name or network address of the instance of SQL Server to which to connect. The port number can be specified after the server name. The correct form of this parameter is either tcp:host,port or tcp:host\\instance; other protocols (np:, lpc:, admin:) are errors.
Integrated Security, IntegratedSecurity, Trusted_Connectionsspi,true,false,yes,noToggle between Windows/Kerberos authentication and SQL authentication.
User ID, uid, user, username<string>The SQL Server login account.
password,pwd<string>The password for the SQL Server account logging on.
Initial Catalog, database<string>The name of the database.
Trust Server Certificate, TrustServerCertificatetrue,false,yes,noSpecifies whether the driver trusts the server certificate when connecting using TLS. Cannot be used toghether with TrustServerCertificateCA
TrustServerCertificateCA<path>Path to a pem, crt or der certificate file. Cannot be used together with TrustServerCertificate
encryptstrict,true,false,yes,no,DANGER_PLAINTEXTSpecifies whether the driver uses TLS to encrypt communication. strict (TDS 8.0) requires the tds80 feature.
Application Name, app, ApplicationName<string>Sets the application name for the connection.
Application Intent, ApplicationIntentReadOnly,ReadWriteDeclares a read-only workload.
Host Name In Certificate, HostNameInCertificate<string>The hostname the server certificate is validated against. Defaults to server.
Workstation ID, WorkstationID, wsid<string>The client / workstation name reported to the server.
Multi Subnet Failover, MultiSubnetFailovertrue,false,yes,noWhen enabled, connections are attempted in parallel to all IP addresses the server resolves to, and the first to succeed is used.
Connect Timeout, Connection Timeout, Timeout<seconds>See Config::connect_timeout.
Packet Size512 to 32768See Config::packet_size.
Server SPN, ServerSPN<string>See Config::server_spn.

SqlClient’s pooling, retry, Command Timeout, Enlist and similar keywords are accepted and ignored. Those this crate can’t honour without changing the connection are errors: MultipleActiveResultSets=true, Failover Partner, Column Encryption Setting=Enabled, AttachDbFilename, Current Language, Server Certificate, User Instance=true, Replication=true, Entra ID Authentication values and Network Library other than dbmssocn.

Source

pub fn from_jdbc_string(s: &str) -> Result<Self>

Creates a new Config from a JDBC connection string.

See from_ado_string method for supported parameters. The URL is split as mssql-jdbc splits it: a value containing ; goes in braces, {like;this}, with }} for a }; other values and all names are trimmed; the last of a property and its synonyms wins.

Trait Implementations§

Source§

impl Clone for Config

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · 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
Source§

impl Drop for Config

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl From<Config> for ConfigBuilder

Source§

fn from(config: Config) -> Self

Converts to this type from the input type.
Source§

impl From<ConfigBuilder> for Config

Source§

fn from(builder: ConfigBuilder) -> Self

Converts to this type from the input type.

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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 = !

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

fn try_from(value: U) -> Result<T, !>

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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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