sqlx_core_guts/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/// | `statement-cache-capacity` | `100` | The maximum number of prepared statements stored in the cache. Set to `0` to disable. |
28/// | `socket` | `None` | Path to the unix domain socket, which will be used instead of TCP if set. |
29///
30/// # Example
31///
32/// ```rust,no_run
33/// # use sqlx_core::error::Error;
34/// # use sqlx_core::connection::{Connection, ConnectOptions};
35/// # use sqlx_core::mysql::{MySqlConnectOptions, MySqlConnection, MySqlSslMode};
36/// #
37/// # fn main() {
38/// # #[cfg(feature = "_rt-async-std")]
39/// # sqlx_rt::async_std::task::block_on::<_, Result<(), Error>>(async move {
40/// // URL connection string
41/// let conn = MySqlConnection::connect("mysql://root:password@localhost/db").await?;
42///
43/// // Manually-constructed options
44/// let conn = MySqlConnectOptions::new()
45///     .host("localhost")
46///     .username("root")
47///     .password("password")
48///     .database("db")
49///     .connect().await?;
50/// # Ok(())
51/// # }).unwrap();
52/// # }
53/// ```
54#[derive(Debug, Clone)]
55pub struct MySqlConnectOptions {
56    pub(crate) host: String,
57    pub(crate) port: u16,
58    pub(crate) socket: Option<PathBuf>,
59    pub(crate) username: String,
60    pub(crate) password: Option<String>,
61    pub(crate) database: Option<String>,
62    pub(crate) ssl_mode: MySqlSslMode,
63    pub(crate) ssl_ca: Option<CertificateInput>,
64    pub(crate) statement_cache_capacity: usize,
65    pub(crate) charset: String,
66    pub(crate) collation: Option<String>,
67    pub(crate) log_settings: LogSettings,
68}
69
70impl Default for MySqlConnectOptions {
71    fn default() -> Self {
72        Self::new()
73    }
74}
75
76impl MySqlConnectOptions {
77    /// Creates a new, default set of options ready for configuration
78    pub fn new() -> Self {
79        Self {
80            port: 3306,
81            host: String::from("localhost"),
82            socket: None,
83            username: String::from("root"),
84            password: None,
85            database: None,
86            charset: String::from("utf8mb4"),
87            collation: None,
88            ssl_mode: MySqlSslMode::Preferred,
89            ssl_ca: None,
90            statement_cache_capacity: 100,
91            log_settings: Default::default(),
92        }
93    }
94
95    /// Sets the name of the host to connect to.
96    ///
97    /// The default behavior when the host is not specified,
98    /// is to connect to localhost.
99    pub fn host(mut self, host: &str) -> Self {
100        self.host = host.to_owned();
101        self
102    }
103
104    /// Sets the port to connect to at the server host.
105    ///
106    /// The default port for MySQL is `3306`.
107    pub fn port(mut self, port: u16) -> Self {
108        self.port = port;
109        self
110    }
111
112    /// Pass a path to a Unix socket. This changes the connection stream from
113    /// TCP to UDS.
114    ///
115    /// By default set to `None`.
116    pub fn socket(mut self, path: impl AsRef<Path>) -> Self {
117        self.socket = Some(path.as_ref().to_path_buf());
118        self
119    }
120
121    /// Sets the username to connect as.
122    pub fn username(mut self, username: &str) -> Self {
123        self.username = username.to_owned();
124        self
125    }
126
127    /// Sets the password to connect with.
128    pub fn password(mut self, password: &str) -> Self {
129        self.password = Some(password.to_owned());
130        self
131    }
132
133    /// Sets the database name.
134    pub fn database(mut self, database: &str) -> Self {
135        self.database = Some(database.to_owned());
136        self
137    }
138
139    /// Sets whether or with what priority a secure SSL TCP/IP connection will be negotiated
140    /// with the server.
141    ///
142    /// By default, the SSL mode is [`Preferred`](MySqlSslMode::Preferred), and the client will
143    /// first attempt an SSL connection but fallback to a non-SSL connection on failure.
144    ///
145    /// # Example
146    ///
147    /// ```rust
148    /// # use sqlx_core::mysql::{MySqlSslMode, MySqlConnectOptions};
149    /// let options = MySqlConnectOptions::new()
150    ///     .ssl_mode(MySqlSslMode::Required);
151    /// ```
152    pub fn ssl_mode(mut self, mode: MySqlSslMode) -> Self {
153        self.ssl_mode = mode;
154        self
155    }
156
157    /// Sets the name of a file containing a list of trusted SSL Certificate Authorities.
158    ///
159    /// # Example
160    ///
161    /// ```rust
162    /// # use sqlx_core::mysql::{MySqlSslMode, MySqlConnectOptions};
163    /// let options = MySqlConnectOptions::new()
164    ///     .ssl_mode(MySqlSslMode::VerifyCa)
165    ///     .ssl_ca("path/to/ca.crt");
166    /// ```
167    pub fn ssl_ca(mut self, file_name: impl AsRef<Path>) -> Self {
168        self.ssl_ca = Some(CertificateInput::File(file_name.as_ref().to_owned()));
169        self
170    }
171
172    /// Sets PEM encoded list of trusted SSL Certificate Authorities.
173    ///
174    /// # Example
175    ///
176    /// ```rust
177    /// # use sqlx_core::mysql::{MySqlSslMode, MySqlConnectOptions};
178    /// let options = MySqlConnectOptions::new()
179    ///     .ssl_mode(MySqlSslMode::VerifyCa)
180    ///     .ssl_ca_from_pem(vec![]);
181    /// ```
182    pub fn ssl_ca_from_pem(mut self, pem_certificate: Vec<u8>) -> Self {
183        self.ssl_ca = Some(CertificateInput::Inline(pem_certificate));
184        self
185    }
186
187    /// Sets the capacity of the connection's statement cache in a number of stored
188    /// distinct statements. Caching is handled using LRU, meaning when the
189    /// amount of queries hits the defined limit, the oldest statement will get
190    /// dropped.
191    ///
192    /// The default cache capacity is 100 statements.
193    pub fn statement_cache_capacity(mut self, capacity: usize) -> Self {
194        self.statement_cache_capacity = capacity;
195        self
196    }
197
198    /// Sets the character set for the connection.
199    ///
200    /// The default character set is `utf8mb4`. This is supported from MySQL 5.5.3.
201    /// If you need to connect to an older version, we recommend you to change this to `utf8`.
202    pub fn charset(mut self, charset: &str) -> Self {
203        self.charset = charset.to_owned();
204        self
205    }
206
207    /// Sets the collation for the connection.
208    ///
209    /// The default collation is derived from the `charset`. Normally, you should only have to set
210    /// the `charset`.
211    pub fn collation(mut self, collation: &str) -> Self {
212        self.collation = Some(collation.to_owned());
213        self
214    }
215}