Skip to main content

ConnectOptions

Struct ConnectOptions 

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

Configuration for opening a DatabaseConnection: connection URL, pool sizing, timeouts, logging, and backend-specific options.

Construct with ConnectOptions::new (or directly from a URL &str), then chain the setter methods before passing to Database::connect.

Implementationsยง

Sourceยง

impl ConnectOptions

Source

pub fn new<T>(url: T) -> Self
where T: Into<String>,

Create new ConnectOptions for a Database by passing in a URI string

Source

pub fn get_url(&self) -> &str

Get the database URL of the pool

Source

pub fn max_connections(&mut self, value: u32) -> &mut Self

Set the maximum number of connections of the pool

Source

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

Get the maximum number of connections of the pool, if set

Source

pub fn min_connections(&mut self, value: u32) -> &mut Self

Set the minimum number of connections of the pool

Source

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

Get the minimum number of connections of the pool, if set

Source

pub fn connect_timeout(&mut self, value: Duration) -> &mut Self

Set the timeout duration when acquiring a connection

Source

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

Get the timeout duration when acquiring a connection, if set

Source

pub fn idle_timeout<T>(&mut self, value: T) -> &mut Self
where T: Into<Option<Duration>>,

Set the idle duration before closing a connection.

Source

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

Get the idle duration before closing a connection, if set

Source

pub fn acquire_timeout(&mut self, value: Duration) -> &mut Self

Set the maximum amount of time to spend waiting for acquiring a connection

Source

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

Get the maximum amount of time to spend waiting for acquiring a connection

Source

pub fn max_lifetime<T>(&mut self, lifetime: T) -> &mut Self
where T: Into<Option<Duration>>,

Set the maximum lifetime of individual connections.

Source

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

Get the maximum lifetime of individual connections, if set

Source

pub fn sqlx_logging(&mut self, value: bool) -> &mut Self

Enable SQLx statement logging (default true)

Source

pub fn get_sqlx_logging(&self) -> bool

Get whether SQLx statement logging is enabled

Source

pub fn record_stmt_in_spans(&mut self, value: bool) -> &mut Self

Enable recording db.statement in tracing spans (default true).

Source

pub fn get_record_stmt_in_spans(&self) -> bool

Get whether db.statement recording in tracing spans is enabled.

Source

pub fn sqlx_logging_level(&mut self, level: LevelFilter) -> &mut Self

Set SQLx statement logging level (default INFO). (ignored if sqlx_logging is false)

Source

pub fn sqlx_slow_statements_logging_settings( &mut self, level: LevelFilter, duration: Duration, ) -> &mut Self

Set SQLx slow statements logging level and duration threshold (default LevelFilter::Off). (ignored if sqlx_logging is false)

Source

pub fn get_sqlx_logging_level(&self) -> LevelFilter

Get the level of SQLx statement logging

Source

pub fn get_sqlx_slow_statements_logging_settings( &self, ) -> (LevelFilter, Duration)

Get the SQLx slow statements logging settings

Source

pub fn sqlcipher_key<T>(&mut self, value: T) -> &mut Self
where T: Into<Cow<'static, str>>,

set key for sqlcipher

Source

pub fn set_schema_search_path<T>(&mut self, schema_search_path: T) -> &mut Self
where T: Into<String>,

Set schema search path (PostgreSQL only)

Source

pub fn set_application_name<T>(&mut self, application_name: T) -> &mut Self
where T: Into<String>,

Set application name (PostgreSQL only)

Source

pub fn statement_timeout(&mut self, value: Duration) -> &mut Self

Set the statement timeout (PostgreSQL only).

This sets the PostgreSQL statement_timeout parameter via the connection options, causing the server to abort any statement that exceeds the specified duration. The timeout is applied at connection time and does not require an extra roundtrip.

Has no effect on MySQL or SQLite connections.

Source

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

Get the statement timeout, if set

Source

pub fn test_before_acquire(&mut self, value: bool) -> &mut Self

If true, the connection will be pinged upon acquiring from the pool (default true).

See test_before_acquire_if_idle_for for the cheaper โ€œonly ping stale connectionsโ€ variant.

Source

pub fn get_test_before_acquire(&self) -> bool

Get whether a pooled connection is pinged on every acquire (default true).

Source

pub fn test_before_acquire_if_idle_for(&mut self, idle: Duration) -> &mut Self

Ping a pooled connection before handing it out, but only once it has been idle for at least idle.

test_before_acquire pings on every acquire, which adds a round-trip to each checkout. This shorthand instead pings only connections that have been idle long enough to plausibly have been dropped by the server, a proxy, or a firewall โ€” the common failure mode โ€” while letting hot connections through untouched.

Calling this sets test_before_acquire to false (SQLx runs the per-acquire ping and this hook, so leaving it enabled would ping on every acquire regardless and defeat the threshold).

It composes with a per-backend map_sqlx_postgres_before_acquire callback (and its MySQL / SQLite counterparts): the idle-ping runs first, then your callback.

ยงExpands to

With no per-backend callback set, this is exactly the following configuration on the underlying sqlx::pool::PoolOptions:

โ“˜
pool_options
    .test_before_acquire(false)
    .before_acquire(move |conn, meta| {
        Box::pin(async move {
            if meta.idle_for >= idle {
                conn.ping().await?;
            }
            Ok(true)
        })
    })

Applies only to pools built through Database::connect. Pools adopted via SqlxPostgresConnector::from_sqlx_postgres_pool (and the MySQL / SQLite equivalents) bypass ConnectOptions entirely โ€” configure before_acquire on your own sqlx::pool::PoolOptions in that case.

ยงExample
let mut opt = ConnectOptions::new("postgres://localhost/db");
opt.test_before_acquire_if_idle_for(Duration::from_secs(30));
assert_eq!(opt.get_test_before_acquire(), false);
Source

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

Get the idle threshold set by test_before_acquire_if_idle_for, if any.

Source

pub fn connect_lazy(&mut self, value: bool) -> &mut Self

If set to true, the db connection pool will be created using SQLxโ€™s connect_lazy method.

Source

pub fn get_connect_lazy(&self) -> bool

Get whether DB connections will be established when the pool is created or only as needed.

Source

pub fn after_connect<F>(&mut self, f: F) -> &mut Self
where F: Fn(DatabaseConnection) -> BoxFuture<'static, Result<(), DbErr>> + Send + Sync + 'static,

Set a callback function that will be called after a new connection is established.

Source

pub fn map_sqlx_mysql_opts<F>(&mut self, f: F) -> &mut Self
where F: Fn(MySqlConnectOptions) -> MySqlConnectOptions + Send + Sync + 'static,

Available on crate feature sqlx-mysql only.

Apply a function to modify the underlying MySqlConnectOptions before creating the connection pool.

Source

pub fn map_sqlx_mysql_pool_opts<F>(&mut self, f: F) -> &mut Self
where F: Fn(PoolOptions<MySql>) -> PoolOptions<MySql> + Send + Sync + 'static,

Available on crate feature sqlx-mysql only.

Apply a function to modify the underlying sqlx::pool::PoolOptions<sqlx::MySql> before creating the connection pool.

Source

pub fn map_sqlx_postgres_opts<F>(&mut self, f: F) -> &mut Self
where F: Fn(PgConnectOptions) -> PgConnectOptions + Send + Sync + 'static,

Available on crate feature sqlx-postgres only.

Apply a function to modify the underlying PgConnectOptions before creating the connection pool.

Source

pub fn map_sqlx_postgres_pool_opts<F>(&mut self, f: F) -> &mut Self
where F: Fn(PoolOptions<Postgres>) -> PoolOptions<Postgres> + Send + Sync + 'static,

Available on crate feature sqlx-postgres only.

Apply a function to modify the underlying sqlx::pool::PoolOptions<sqlx::Postgres> before creating the connection pool.

Source

pub fn map_sqlx_sqlite_opts<F>(&mut self, f: F) -> &mut Self

Available on crate feature sqlx-sqlite only.

Apply a function to modify the underlying SqliteConnectOptions before creating the connection pool.

Source

pub fn map_sqlx_sqlite_pool_opts<F>(&mut self, f: F) -> &mut Self
where F: Fn(PoolOptions<Sqlite>) -> PoolOptions<Sqlite> + Send + Sync + 'static,

Available on crate feature sqlx-sqlite only.

Apply a function to modify the underlying sqlx::pool::PoolOptions<sqlx::Sqlite> before creating the connection pool.

Source

pub fn map_sqlx_mysql_before_acquire<F>(&mut self, f: F) -> &mut Self
where F: for<'c> Fn(&'c mut MySqlConnection, PoolConnectionMetadata) -> BoxFuture<'c, Result<bool, Error>> + Send + Sync + 'static,

Available on crate feature sqlx-mysql only.

Set a before_acquire callback run on an idle pooled MySQL connection before it is handed out.

Return Ok(true) to use the connection, or Ok(false)/Err(_) to discard it and let the pool try another (opening a fresh one if needed). Composes after the idle-ping installed by test_before_acquire_if_idle_for โ€” that runs first, then this callback.

Applies only to pools built through Database::connect, not to pools adopted via SqlxMySqlConnector::from_sqlx_mysql_pool.

Source

pub fn map_sqlx_postgres_before_acquire<F>(&mut self, f: F) -> &mut Self
where F: for<'c> Fn(&'c mut PgConnection, PoolConnectionMetadata) -> BoxFuture<'c, Result<bool, Error>> + Send + Sync + 'static,

Available on crate feature sqlx-postgres only.

Set a before_acquire callback run on an idle pooled PostgreSQL connection before it is handed out.

Return Ok(true) to use the connection, or Ok(false)/Err(_) to discard it and let the pool try another (opening a fresh one if needed). Composes after the idle-ping installed by test_before_acquire_if_idle_for โ€” that runs first, then this callback.

Applies only to pools built through Database::connect, not to pools adopted via SqlxPostgresConnector::from_sqlx_postgres_pool.

ยงExample
let mut opt = ConnectOptions::new("postgres://localhost/db");
opt.map_sqlx_postgres_before_acquire(|_conn, meta| {
    Box::pin(async move {
        // Discard (and transparently replace) connections older than 10 minutes,
        // rather than pinging on every acquire.
        Ok(meta.age < Duration::from_secs(600))
    })
});
Source

pub fn map_sqlx_sqlite_before_acquire<F>(&mut self, f: F) -> &mut Self
where F: for<'c> Fn(&'c mut SqliteConnection, PoolConnectionMetadata) -> BoxFuture<'c, Result<bool, Error>> + Send + Sync + 'static,

Available on crate feature sqlx-sqlite only.

Set a before_acquire callback run on an idle pooled SQLite connection before it is handed out.

Return Ok(true) to use the connection, or Ok(false)/Err(_) to discard it and let the pool try another (opening a fresh one if needed). Composes after the idle-ping installed by test_before_acquire_if_idle_for โ€” that runs first, then this callback.

Applies only to pools built through Database::connect, not to pools adopted via SqlxSqliteConnector::from_sqlx_sqlite_pool.

Sourceยง

impl ConnectOptions

Source

pub fn sqlx_pool_options<DB>(self) -> PoolOptions<DB>
where DB: Database,

Available on crate feature sqlx-dep only.

Trait Implementationsยง

Sourceยง

impl Clone for ConnectOptions

Sourceยง

fn clone(&self) -> ConnectOptions

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 ConnectOptions

Sourceยง

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

Formats the value using the given formatter. Read more
Sourceยง

impl<T> From<T> for ConnectOptions
where T: Into<String>,

Sourceยง

fn from(s: T) -> ConnectOptions

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> IntoEither for T

Sourceยง

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Sourceยง

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
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 = 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