sqlx_core_oldapi/mysql/options/
mod.rs

1use std::path::{Path, PathBuf};
2
3mod connect;
4mod parse;
5mod ssl_mode;
6
7use crate::{connection::LogSettings, net::CertificateInput};
8pub use ssl_mode::MySqlSslMode;
9
10/// Options and flags which can be used to configure a MySQL connection.
11///
12/// A value of `MySqlConnectOptions` can be parsed from a connection URL,
13/// as described by [MySQL](https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-reference-jdbc-url-format.html).
14///
15/// The generic format of the connection URL:
16///
17/// ```text
18/// mysql://[host][/database][?properties]
19/// ```
20///
21/// ## Properties
22///
23/// |Parameter|Default|Description|
24/// |---------|-------|-----------|
25/// | `ssl-mode` | `PREFERRED` | Determines whether or with what priority a secure SSL TCP/IP connection will be negotiated. See [`MySqlSslMode`]. |
26/// | `ssl-ca` | `None` | Sets the name of a file containing a list of trusted SSL Certificate Authorities. |
27/// | `ssl-cert` | `None` | Sets the name of a file containing a client SSL certificate to authenticate the connection to the server |
28/// | `ssl-key` | `None` | Sets the name of a file containing a secret SSL key for the client certificate. |
29/// | `statement-cache-capacity` | `100` | The maximum number of prepared statements stored in the cache. Set to `0` to disable. |
30/// | `socket` | `None` | Path to the unix domain socket, which will be used instead of TCP if set. |
31///
32/// # Example
33///
34/// ```rust,no_run
35/// # use sqlx_core_oldapi::error::Error;
36/// # use sqlx_core_oldapi::connection::{Connection, ConnectOptions};
37/// # use sqlx_core_oldapi::mysql::{MySqlConnectOptions, MySqlConnection, MySqlSslMode};
38/// #
39/// # fn main() {
40/// # #[cfg(feature = "_rt-async-std")]
41/// # sqlx_rt::async_std::task::block_on::<_, Result<(), Error>>(async move {
42/// // URL connection string
43/// let conn = MySqlConnection::connect("mysql://root:password@localhost/db").await?;
44///
45/// // Manually-constructed options
46/// let conn = MySqlConnectOptions::new()
47///     .host("localhost")
48///     .username("root")
49///     .password("password")
50///     .database("db")
51///     .connect().await?;
52/// # Ok(())
53/// # }).unwrap();
54/// # }
55/// ```
56#[derive(Debug, Clone)]
57pub struct MySqlConnectOptions {
58    pub(crate) host: String,
59    pub(crate) port: u16,
60    pub(crate) socket: Option<PathBuf>,
61    pub(crate) username: String,
62    pub(crate) password: Option<String>,
63    pub(crate) database: Option<String>,
64    pub(crate) ssl_mode: MySqlSslMode,
65    pub(crate) ssl_ca: Option<CertificateInput>,
66    pub(crate) ssl_client_cert: Option<CertificateInput>,
67    pub(crate) ssl_client_key: Option<CertificateInput>,
68    pub(crate) statement_cache_capacity: usize,
69    pub(crate) charset: String,
70    pub(crate) collation: Option<String>,
71    pub(crate) log_settings: LogSettings,
72    pub(crate) pipes_as_concat: bool,
73}
74
75impl Default for MySqlConnectOptions {
76    fn default() -> Self {
77        Self::new()
78    }
79}
80
81impl MySqlConnectOptions {
82    /// Creates a new, default set of options ready for configuration
83    pub fn new() -> Self {
84        Self {
85            port: 3306,
86            host: String::from("localhost"),
87            socket: None,
88            username: String::from("root"),
89            password: None,
90            database: None,
91            charset: String::from("utf8mb4"),
92            collation: None,
93            ssl_mode: MySqlSslMode::Preferred,
94            ssl_ca: None,
95            ssl_client_cert: None,
96            ssl_client_key: None,
97            statement_cache_capacity: 100,
98            log_settings: Default::default(),
99            pipes_as_concat: true,
100        }
101    }
102
103    /// Sets the name of the host to connect to.
104    ///
105    /// The default behavior when the host is not specified,
106    /// is to connect to localhost.
107    pub fn host(mut self, host: &str) -> Self {
108        self.host = host.to_owned();
109        self
110    }
111
112    /// Sets the port to connect to at the server host.
113    ///
114    /// The default port for MySQL is `3306`.
115    pub fn port(mut self, port: u16) -> Self {
116        self.port = port;
117        self
118    }
119
120    /// Pass a path to a Unix socket. This changes the connection stream from
121    /// TCP to UDS.
122    ///
123    /// By default set to `None`.
124    pub fn socket(mut self, path: impl AsRef<Path>) -> Self {
125        self.socket = Some(path.as_ref().to_path_buf());
126        self
127    }
128
129    /// Sets the username to connect as.
130    pub fn username(mut self, username: &str) -> Self {
131        self.username = username.to_owned();
132        self
133    }
134
135    /// Sets the password to connect with.
136    pub fn password(mut self, password: &str) -> Self {
137        self.password = Some(password.to_owned());
138        self
139    }
140
141    /// Sets the database name.
142    pub fn database(mut self, database: &str) -> Self {
143        self.database = Some(database.to_owned());
144        self
145    }
146
147    /// Sets whether or with what priority a secure SSL TCP/IP connection will be negotiated
148    /// with the server.
149    ///
150    /// By default, the SSL mode is [`Preferred`](MySqlSslMode::Preferred), and the client will
151    /// first attempt an SSL connection but fallback to a non-SSL connection on failure.
152    ///
153    /// # Example
154    ///
155    /// ```rust
156    /// # use sqlx_core_oldapi::mysql::{MySqlSslMode, MySqlConnectOptions};
157    /// let options = MySqlConnectOptions::new()
158    ///     .ssl_mode(MySqlSslMode::Required);
159    /// ```
160    pub fn ssl_mode(mut self, mode: MySqlSslMode) -> Self {
161        self.ssl_mode = mode;
162        self
163    }
164
165    /// Sets the name of a file containing a list of trusted SSL Certificate Authorities.
166    ///
167    /// # Example
168    ///
169    /// ```rust
170    /// # use sqlx_core_oldapi::mysql::{MySqlSslMode, MySqlConnectOptions};
171    /// let options = MySqlConnectOptions::new()
172    ///     .ssl_mode(MySqlSslMode::VerifyCa)
173    ///     .ssl_ca("path/to/ca.crt");
174    /// ```
175    pub fn ssl_ca(mut self, file_name: impl AsRef<Path>) -> Self {
176        self.ssl_ca = Some(CertificateInput::File(file_name.as_ref().to_owned()));
177        self
178    }
179
180    /// Sets PEM encoded list of trusted SSL Certificate Authorities.
181    ///
182    /// # Example
183    ///
184    /// ```rust
185    /// # use sqlx_core_oldapi::mysql::{MySqlSslMode, MySqlConnectOptions};
186    /// let options = MySqlConnectOptions::new()
187    ///     .ssl_mode(MySqlSslMode::VerifyCa)
188    ///     .ssl_ca_from_pem(vec![]);
189    /// ```
190    pub fn ssl_ca_from_pem(mut self, pem_certificate: Vec<u8>) -> Self {
191        self.ssl_ca = Some(CertificateInput::Inline(pem_certificate));
192        self
193    }
194
195    /// Sets the name of a file containing SSL client certificate.
196    ///
197    /// # Example
198    ///
199    /// ```rust
200    /// # use sqlx_core_oldapi::mysql::{MySqlSslMode, MySqlConnectOptions};
201    /// let options = MySqlConnectOptions::new()
202    ///     .ssl_mode(MySqlSslMode::VerifyCa)
203    ///     .ssl_client_cert("path/to/client.crt");
204    /// ```
205    pub fn ssl_client_cert(mut self, cert: impl AsRef<Path>) -> Self {
206        self.ssl_client_cert = Some(CertificateInput::File(cert.as_ref().to_path_buf()));
207        self
208    }
209
210    /// Sets the name of a file containing SSL client key.
211    ///
212    /// # Example
213    ///
214    /// ```rust
215    /// # use sqlx_core_oldapi::mysql::{MySqlSslMode, MySqlConnectOptions};
216    /// let options = MySqlConnectOptions::new()
217    ///     .ssl_mode(MySqlSslMode::VerifyCa)
218    ///     .ssl_client_key("path/to/client.key");
219    /// ```
220    pub fn ssl_client_key(mut self, key: impl AsRef<Path>) -> Self {
221        self.ssl_client_key = Some(CertificateInput::File(key.as_ref().to_path_buf()));
222        self
223    }
224
225    /// Sets the capacity of the connection's statement cache in a number of stored
226    /// distinct statements. Caching is handled using LRU, meaning when the
227    /// amount of queries hits the defined limit, the oldest statement will get
228    /// dropped.
229    ///
230    /// The default cache capacity is 100 statements.
231    pub fn statement_cache_capacity(mut self, capacity: usize) -> Self {
232        self.statement_cache_capacity = capacity;
233        self
234    }
235
236    /// Sets the character set for the connection.
237    ///
238    /// The default character set is `utf8mb4`. This is supported from MySQL 5.5.3.
239    /// If you need to connect to an older version, we recommend you to change this to `utf8`.
240    pub fn charset(mut self, charset: &str) -> Self {
241        self.charset = charset.to_owned();
242        self
243    }
244
245    /// Sets the collation for the connection.
246    ///
247    /// The default collation is derived from the `charset`. Normally, you should only have to set
248    /// the `charset`.
249    pub fn collation(mut self, collation: &str) -> Self {
250        self.collation = Some(collation.to_owned());
251        self
252    }
253
254    /// Sets the flag that enables or disables the `PIPES_AS_CONCAT` connection setting
255    ///
256    /// The default value is set to true, but some MySql databases such as PlanetScale
257    /// error out with this connection setting so it needs to be set false in such
258    /// cases.
259    pub fn pipes_as_concat(mut self, flag_val: bool) -> Self {
260        self.pipes_as_concat = flag_val;
261        self
262    }
263}