sqlx_core/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 pub(crate) pipes_as_concat: bool,
69}
70
71impl Default for MySqlConnectOptions {
72 fn default() -> Self {
73 Self::new()
74 }
75}
76
77impl MySqlConnectOptions {
78 /// Creates a new, default set of options ready for configuration
79 pub fn new() -> Self {
80 Self {
81 port: 3306,
82 host: String::from("localhost"),
83 socket: None,
84 username: String::from("root"),
85 password: None,
86 database: None,
87 charset: String::from("utf8mb4"),
88 collation: None,
89 ssl_mode: MySqlSslMode::Disabled,
90 ssl_ca: None,
91 statement_cache_capacity: 100,
92 log_settings: Default::default(),
93 pipes_as_concat: true,
94 }
95 }
96
97 /// Sets the name of the host to connect to.
98 ///
99 /// The default behavior when the host is not specified,
100 /// is to connect to localhost.
101 pub fn host(mut self, host: &str) -> Self {
102 self.host = host.to_owned();
103 self
104 }
105
106 /// Sets the port to connect to at the server host.
107 ///
108 /// The default port for MySQL is `3306`.
109 pub fn port(mut self, port: u16) -> Self {
110 self.port = port;
111 self
112 }
113
114 /// Pass a path to a Unix socket. This changes the connection stream from
115 /// TCP to UDS.
116 ///
117 /// By default set to `None`.
118 pub fn socket(mut self, path: impl AsRef<Path>) -> Self {
119 self.socket = Some(path.as_ref().to_path_buf());
120 self
121 }
122
123 /// Sets the username to connect as.
124 pub fn username(mut self, username: &str) -> Self {
125 self.username = username.to_owned();
126 self
127 }
128
129 /// Sets the password to connect with.
130 pub fn password(mut self, password: &str) -> Self {
131 self.password = Some(password.to_owned());
132 self
133 }
134
135 /// Sets the database name.
136 pub fn database(mut self, database: &str) -> Self {
137 self.database = Some(database.to_owned());
138 self
139 }
140
141 /// Sets whether or with what priority a secure SSL TCP/IP connection will be negotiated
142 /// with the server.
143 ///
144 /// By default, the SSL mode is [`Preferred`](MySqlSslMode::Preferred), and the client will
145 /// first attempt an SSL connection but fallback to a non-SSL connection on failure.
146 ///
147 /// # Example
148 ///
149 /// ```rust
150 /// # use sqlx_core::mysql::{MySqlSslMode, MySqlConnectOptions};
151 /// let options = MySqlConnectOptions::new()
152 /// .ssl_mode(MySqlSslMode::Required);
153 /// ```
154 pub fn ssl_mode(mut self, mode: MySqlSslMode) -> Self {
155 self.ssl_mode = mode;
156 self
157 }
158
159 /// Sets the name of a file containing a list of trusted SSL Certificate Authorities.
160 ///
161 /// # Example
162 ///
163 /// ```rust
164 /// # use sqlx_core::mysql::{MySqlSslMode, MySqlConnectOptions};
165 /// let options = MySqlConnectOptions::new()
166 /// .ssl_mode(MySqlSslMode::VerifyCa)
167 /// .ssl_ca("path/to/ca.crt");
168 /// ```
169 pub fn ssl_ca(mut self, file_name: impl AsRef<Path>) -> Self {
170 self.ssl_ca = Some(CertificateInput::File(file_name.as_ref().to_owned()));
171 self
172 }
173
174 /// Sets PEM encoded list of trusted SSL Certificate Authorities.
175 ///
176 /// # Example
177 ///
178 /// ```rust
179 /// # use sqlx_core::mysql::{MySqlSslMode, MySqlConnectOptions};
180 /// let options = MySqlConnectOptions::new()
181 /// .ssl_mode(MySqlSslMode::VerifyCa)
182 /// .ssl_ca_from_pem(vec![]);
183 /// ```
184 pub fn ssl_ca_from_pem(mut self, pem_certificate: Vec<u8>) -> Self {
185 self.ssl_ca = Some(CertificateInput::Inline(pem_certificate));
186 self
187 }
188
189 /// Sets the capacity of the connection's statement cache in a number of stored
190 /// distinct statements. Caching is handled using LRU, meaning when the
191 /// amount of queries hits the defined limit, the oldest statement will get
192 /// dropped.
193 ///
194 /// The default cache capacity is 100 statements.
195 pub fn statement_cache_capacity(mut self, capacity: usize) -> Self {
196 self.statement_cache_capacity = capacity;
197 self
198 }
199
200 /// Sets the character set for the connection.
201 ///
202 /// The default character set is `utf8mb4`. This is supported from MySQL 5.5.3.
203 /// If you need to connect to an older version, we recommend you to change this to `utf8`.
204 pub fn charset(mut self, charset: &str) -> Self {
205 self.charset = charset.to_owned();
206 self
207 }
208
209 /// Sets the collation for the connection.
210 ///
211 /// The default collation is derived from the `charset`. Normally, you should only have to set
212 /// the `charset`.
213 pub fn collation(mut self, collation: &str) -> Self {
214 self.collation = Some(collation.to_owned());
215 self
216 }
217
218 /// Sets the flag that enables or disables the `PIPES_AS_CONCAT` connection setting
219 ///
220 /// The default value is set to true, but some MySql databases such as PlanetScale
221 /// error out with this connection setting so it needs to be set false in such
222 /// cases.
223 pub fn pipes_as_concat(mut self, flag_val: bool) -> Self {
224 self.pipes_as_concat = flag_val;
225 self
226 }
227}