Skip to main content

sqlx_mysql/options/
mod.rs

1use sqlx_core::net::UrlHost;
2use std::{
3    path::{Path, PathBuf},
4    sync::{Arc, OnceLock},
5};
6
7mod connect;
8mod parse;
9mod ssl_mode;
10
11use crate::{connection::LogSettings, net::tls::CertificateInput};
12use sqlx_core::net::tls::TlsConnector;
13pub use ssl_mode::MySqlSslMode;
14
15/// Options and flags which can be used to configure a MySQL connection.
16///
17/// A value of `MySqlConnectOptions` can be parsed from a connection URL,
18/// as described by [MySQL](https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-reference-jdbc-url-format.html).
19///
20/// The generic format of the connection URL:
21///
22/// ```text
23/// mysql://[host][/database][?properties]
24/// ```
25///
26/// This type also implements [`FromStr`][std::str::FromStr] so you can parse it from a string
27/// containing a connection URL and then further adjust options if necessary (see example below).
28///
29/// ## Properties
30///
31/// |Parameter|Default|Description|
32/// |---------|-------|-----------|
33/// | `ssl-mode` | `PREFERRED` | Determines whether or with what priority a secure SSL TCP/IP connection will be negotiated. See [`MySqlSslMode`]. |
34/// | `ssl-ca` | `None` | Sets the name of a file containing a list of trusted SSL Certificate Authorities. |
35/// | `statement-cache-capacity` | `100` | The maximum number of prepared statements stored in the cache. Set to `0` to disable. |
36/// | `socket` | `None` | Path to the unix domain socket, which will be used instead of TCP if set. |
37///
38/// # Example
39///
40/// ```rust,no_run
41/// # async fn example() -> sqlx::Result<()> {
42/// use sqlx::{Connection, ConnectOptions};
43/// use sqlx::mysql::{MySqlConnectOptions, MySqlConnection, MySqlPool, MySqlSslMode};
44///
45/// // URL connection string
46/// let conn = MySqlConnection::connect("mysql://root:password@localhost/db").await?;
47///
48/// // Manually-constructed options
49/// let conn = MySqlConnectOptions::new()
50///     .host("localhost")
51///     .username("root")
52///     .password("password")
53///     .database("db")
54///     .connect().await?;
55///
56/// // Modifying options parsed from a string
57/// let mut opts: MySqlConnectOptions = "mysql://root:password@localhost/db".parse()?;
58///
59/// // Change the log verbosity level for queries.
60/// // Information about SQL queries is logged at `DEBUG` level by default.
61/// opts = opts.log_statements(log::LevelFilter::Trace);
62///
63/// let pool = MySqlPool::connect_with(opts).await?;
64/// # Ok(())
65/// # }
66/// ```
67#[derive(Debug, Clone)]
68pub struct MySqlConnectOptions {
69    pub(crate) host: UrlHost,
70    pub(crate) port: u16,
71    pub(crate) socket: Option<PathBuf>,
72    pub(crate) username: String,
73    pub(crate) password: Option<String>,
74    pub(crate) database: Option<String>,
75    pub(crate) tls_sni_servername: Option<String>,
76    pub(crate) ssl_options: SslOptions,
77    pub(crate) statement_cache_capacity: usize,
78    pub(crate) charset: String,
79    pub(crate) collation: Option<String>,
80    pub(crate) log_settings: LogSettings,
81    pub(crate) pipes_as_concat: bool,
82    pub(crate) enable_cleartext_plugin: bool,
83    pub(crate) no_engine_substitution: bool,
84    pub(crate) timezone: Option<String>,
85    pub(crate) set_names: bool,
86    pub(crate) found_rows: bool,
87}
88
89impl Default for MySqlConnectOptions {
90    fn default() -> Self {
91        Self::new()
92    }
93}
94
95#[derive(Debug, Clone)]
96pub(crate) struct SslOptions {
97    pub(crate) ssl_mode: MySqlSslMode,
98    pub(crate) ssl_ca: Option<CertificateInput>,
99    pub(crate) ssl_client_cert: Option<CertificateInput>,
100    pub(crate) ssl_client_key: Option<CertificateInput>,
101    pub(crate) cached_connector: Arc<OnceLock<TlsConnector>>,
102}
103
104impl MySqlConnectOptions {
105    /// Creates a new, default set of options ready for configuration
106    pub fn new() -> Self {
107        Self {
108            port: 3306,
109            host: UrlHost::localhost(),
110            socket: None,
111            username: String::from("root"),
112            password: None,
113            database: None,
114            charset: String::from("utf8mb4"),
115            collation: None,
116            tls_sni_servername: None,
117            ssl_options: SslOptions {
118                ssl_mode: MySqlSslMode::Preferred,
119                ssl_ca: None,
120                ssl_client_cert: None,
121                ssl_client_key: None,
122                cached_connector: Arc::new(OnceLock::new()),
123            },
124            statement_cache_capacity: 100,
125            log_settings: Default::default(),
126            pipes_as_concat: true,
127            enable_cleartext_plugin: false,
128            no_engine_substitution: true,
129            timezone: Some(String::from("+00:00")),
130            set_names: true,
131            found_rows: true,
132        }
133    }
134
135    /// Sets the name of the host to connect to.
136    ///
137    /// The default behavior when the host is not specified,
138    /// is to connect to localhost.
139    pub fn host(mut self, host: &str) -> Self {
140        self.host.set(host);
141        self
142    }
143
144    /// Overrides the TLS server name used for SNI and hostname verification.
145    ///
146    /// By default, the host from `MySqlConnectOptions` is used.
147    ///
148    /// # Example
149    ///
150    /// ```rust
151    /// # use sqlx_mysql::MySqlConnectOptions;
152    /// let _options = MySqlConnectOptions::new()
153    ///     .host("haproxy.example.com")
154    ///     .tls_sni_servername("mysql.example.com");
155    /// ```
156    pub fn tls_sni_servername(mut self, server_name: &str) -> Self {
157        self.tls_sni_servername = Some(server_name.to_owned());
158        self
159    }
160
161    /// Sets the port to connect to at the server host.
162    ///
163    /// The default port for MySQL is `3306`.
164    pub fn port(mut self, port: u16) -> Self {
165        self.port = port;
166        self
167    }
168
169    /// Pass a path to a Unix socket. This changes the connection stream from
170    /// TCP to UDS.
171    ///
172    /// By default set to `None`.
173    pub fn socket(mut self, path: impl AsRef<Path>) -> Self {
174        self.socket = Some(path.as_ref().to_path_buf());
175        self
176    }
177
178    /// Sets the username to connect as.
179    pub fn username(mut self, username: &str) -> Self {
180        username.clone_into(&mut self.username);
181        self
182    }
183
184    /// Sets the password to connect with.
185    pub fn password(mut self, password: &str) -> Self {
186        self.password = Some(password.to_owned());
187        self
188    }
189
190    /// Sets the database name.
191    pub fn database(mut self, database: &str) -> Self {
192        self.database = Some(database.to_owned());
193        self
194    }
195
196    fn ssl_options_mut(&mut self) -> &mut SslOptions {
197        Arc::make_mut(&mut self.ssl_options.cached_connector).take();
198        &mut self.ssl_options
199    }
200
201    /// Sets whether or with what priority a secure SSL TCP/IP connection will be negotiated
202    /// with the server.
203    ///
204    /// By default, the SSL mode is [`Preferred`](MySqlSslMode::Preferred), and the client will
205    /// first attempt an SSL connection but fallback to a non-SSL connection on failure.
206    ///
207    /// # Example
208    ///
209    /// ```rust
210    /// # use sqlx_mysql::{MySqlSslMode, MySqlConnectOptions};
211    /// let options = MySqlConnectOptions::new()
212    ///     .ssl_mode(MySqlSslMode::Required);
213    /// ```
214    pub fn ssl_mode(mut self, mode: MySqlSslMode) -> Self {
215        self.ssl_options_mut().ssl_mode = mode;
216        self
217    }
218
219    /// Sets the name of a file containing a list of trusted SSL Certificate Authorities.
220    ///
221    /// # Example
222    ///
223    /// ```rust
224    /// # use sqlx_mysql::{MySqlSslMode, MySqlConnectOptions};
225    /// let options = MySqlConnectOptions::new()
226    ///     .ssl_mode(MySqlSslMode::VerifyCa)
227    ///     .ssl_ca("path/to/ca.crt");
228    /// ```
229    pub fn ssl_ca(mut self, file_name: impl AsRef<Path>) -> Self {
230        self.ssl_options_mut().ssl_ca = Some(CertificateInput::File(file_name.as_ref().to_owned()));
231        self
232    }
233
234    /// Sets PEM encoded list of trusted SSL Certificate Authorities.
235    ///
236    /// # Example
237    ///
238    /// ```rust
239    /// # use sqlx_mysql::{MySqlSslMode, MySqlConnectOptions};
240    /// let options = MySqlConnectOptions::new()
241    ///     .ssl_mode(MySqlSslMode::VerifyCa)
242    ///     .ssl_ca_from_pem(vec![]);
243    /// ```
244    pub fn ssl_ca_from_pem(mut self, pem_certificate: Vec<u8>) -> Self {
245        self.ssl_options_mut().ssl_ca = Some(CertificateInput::Inline(pem_certificate));
246        self
247    }
248
249    /// Sets the name of a file containing SSL client certificate.
250    ///
251    /// # Example
252    ///
253    /// ```rust
254    /// # use sqlx_mysql::{MySqlSslMode, MySqlConnectOptions};
255    /// let options = MySqlConnectOptions::new()
256    ///     .ssl_mode(MySqlSslMode::VerifyCa)
257    ///     .ssl_client_cert("path/to/client.crt");
258    /// ```
259    pub fn ssl_client_cert(mut self, cert: impl AsRef<Path>) -> Self {
260        self.ssl_options_mut().ssl_client_cert =
261            Some(CertificateInput::File(cert.as_ref().to_path_buf()));
262        self
263    }
264
265    /// Sets the SSL client certificate as a PEM-encoded byte slice.
266    ///
267    /// This should be an ASCII-encoded blob that starts with `-----BEGIN CERTIFICATE-----`.
268    ///
269    /// # Example
270    /// Note: embedding SSL certificates and keys in the binary is not advised.
271    /// This is for illustration purposes only.
272    ///
273    /// ```rust
274    /// # use sqlx_mysql::{MySqlSslMode, MySqlConnectOptions};
275    ///
276    /// const CERT: &[u8] = b"\
277    /// -----BEGIN CERTIFICATE-----
278    /// <Certificate data here.>
279    /// -----END CERTIFICATE-----";
280    ///
281    /// let options = MySqlConnectOptions::new()
282    ///     .ssl_mode(MySqlSslMode::VerifyCa)
283    ///     .ssl_client_cert_from_pem(CERT);
284    /// ```
285    pub fn ssl_client_cert_from_pem(mut self, cert: impl AsRef<[u8]>) -> Self {
286        self.ssl_options_mut().ssl_client_cert =
287            Some(CertificateInput::Inline(cert.as_ref().to_vec()));
288        self
289    }
290
291    /// Sets the name of a file containing SSL client key.
292    ///
293    /// # Example
294    ///
295    /// ```rust
296    /// # use sqlx_mysql::{MySqlSslMode, MySqlConnectOptions};
297    /// let options = MySqlConnectOptions::new()
298    ///     .ssl_mode(MySqlSslMode::VerifyCa)
299    ///     .ssl_client_key("path/to/client.key");
300    /// ```
301    pub fn ssl_client_key(mut self, key: impl AsRef<Path>) -> Self {
302        self.ssl_options_mut().ssl_client_key =
303            Some(CertificateInput::File(key.as_ref().to_path_buf()));
304        self
305    }
306
307    /// Sets the SSL client key as a PEM-encoded byte slice.
308    ///
309    /// This should be an ASCII-encoded blob that starts with `-----BEGIN PRIVATE KEY-----`.
310    ///
311    /// # Example
312    /// Note: embedding SSL certificates and keys in the binary is not advised.
313    /// This is for illustration purposes only.
314    ///
315    /// ```rust
316    /// # use sqlx_mysql::{MySqlSslMode, MySqlConnectOptions};
317    ///
318    /// const KEY: &[u8] = b"\
319    /// -----BEGIN PRIVATE KEY-----
320    /// <Private key data here.>
321    /// -----END PRIVATE KEY-----";
322    ///
323    /// let options = MySqlConnectOptions::new()
324    ///     .ssl_mode(MySqlSslMode::VerifyCa)
325    ///     .ssl_client_key_from_pem(KEY);
326    /// ```
327    pub fn ssl_client_key_from_pem(mut self, key: impl AsRef<[u8]>) -> Self {
328        self.ssl_options_mut().ssl_client_key =
329            Some(CertificateInput::Inline(key.as_ref().to_vec()));
330        self
331    }
332
333    /// Sets the capacity of the connection's statement cache in a number of stored
334    /// distinct statements. Caching is handled using LRU, meaning when the
335    /// amount of queries hits the defined limit, the oldest statement will get
336    /// dropped.
337    ///
338    /// The default cache capacity is 100 statements.
339    pub fn statement_cache_capacity(mut self, capacity: usize) -> Self {
340        self.statement_cache_capacity = capacity;
341        self
342    }
343
344    /// Sets the character set for the connection.
345    ///
346    /// The default character set is `utf8mb4`. This is supported from MySQL 5.5.3.
347    /// If you need to connect to an older version, we recommend you to change this to `utf8`.
348    ///
349    /// Implies [`.set_names(true)`][Self::set_names()].
350    pub fn charset(mut self, charset: &str) -> Self {
351        self.set_names = true;
352        charset.clone_into(&mut self.charset);
353        self
354    }
355
356    /// Sets the collation for the connection.
357    ///
358    /// The default collation is derived on the server from the `charset`, if set.
359    /// Normally, you should only have to set the `charset`.
360    ///
361    /// If setting this, it is recommended to also set [`charset`][Self::charset()].
362    ///
363    /// Implies [`.set_names(true)`][Self::set_names()].
364    pub fn collation(mut self, collation: &str) -> Self {
365        self.set_names = true;
366        self.collation = Some(collation.to_owned());
367        self
368    }
369
370    /// Sets the flag that enables or disables the `PIPES_AS_CONCAT` connection setting
371    ///
372    /// The default value is set to true, but some MySql databases such as PlanetScale
373    /// error out with this connection setting so it needs to be set false in such
374    /// cases.
375    pub fn pipes_as_concat(mut self, flag_val: bool) -> Self {
376        self.pipes_as_concat = flag_val;
377        self
378    }
379
380    /// Enables mysql_clear_password plugin support.
381    ///
382    /// Security Note:
383    /// Sending passwords as cleartext may be a security problem in some
384    /// configurations. Without additional defensive configuration like
385    /// ssl-mode=VERIFY_IDENTITY, an attacker can compromise a router
386    /// and trick the application into divulging its credentials.
387    ///
388    /// It is strongly recommended to set `.ssl_mode` to `Required`,
389    /// `VerifyCa`, or `VerifyIdentity` when enabling cleartext plugin.
390    pub fn enable_cleartext_plugin(mut self, flag_val: bool) -> Self {
391        self.enable_cleartext_plugin = flag_val;
392        self
393    }
394
395    #[deprecated = "renamed to .no_engine_substitution()"]
396    pub fn no_engine_subsitution(self, flag_val: bool) -> Self {
397        self.no_engine_substitution(flag_val)
398    }
399
400    /// Flag that enables or disables the `NO_ENGINE_SUBSTITUTION` sql_mode setting after
401    /// connection.
402    ///
403    /// If not set, if the available storage engine specified by a `CREATE TABLE` is not available,
404    /// a warning is given and the default storage engine is used instead.
405    ///
406    /// By default, this is `true` (`NO_ENGINE_SUBSTITUTION` is passed, forbidding engine
407    /// substitution).
408    ///
409    /// <https://mariadb.com/kb/en/sql-mode/>
410    pub fn no_engine_substitution(mut self, flag_val: bool) -> Self {
411        self.no_engine_substitution = flag_val;
412        self
413    }
414
415    /// If `Some`, sets the `time_zone` option to the given string after connecting to the database.
416    ///
417    /// If `None`, no `time_zone` parameter is sent; the server timezone will be used instead.
418    ///
419    /// Defaults to `Some(String::from("+00:00"))` to ensure all timestamps are in UTC.
420    ///
421    /// ### Warning
422    /// Changing this setting from its default will apply an unexpected skew to any
423    /// `time::OffsetDateTime` or `chrono::DateTime<Utc>` value, whether passed as a parameter or
424    /// decoded as a result. `TIMESTAMP` values are not encoded with their UTC offset in the MySQL
425    /// protocol, so encoding and decoding of these types assumes the server timezone is *always*
426    /// UTC.
427    ///
428    /// If you are changing this option, ensure your application only uses
429    /// `time::PrimitiveDateTime` or `chrono::NaiveDateTime` and that it does not assume these
430    /// timestamps can be placed on a real timeline without applying the proper offset.
431    pub fn timezone(mut self, value: impl Into<Option<String>>) -> Self {
432        self.timezone = value.into();
433        self
434    }
435
436    /// If enabled, [`.charset()`] and [`.collation()`] are set with the appropriate command.
437    ///
438    /// If only `.charset()`
439    ///
440    /// This ensures the connection uses the specified character set and collation.
441    ///
442    /// Enabled by default.
443    ///
444    /// ### Warning
445    /// If this is disabled and the default charset is not binary-compatible with UTF-8, query
446    /// strings, column names and string values will likely not decode (or encode) correctly, which
447    /// may result in unexpected errors or garbage outputs at runtime.
448    ///
449    /// For proper functioning, you *must* ensure the server is using a binary-compatible charset,
450    /// such as ASCII or Latin-1 (ISO 8859-1), and that you do not pass any strings containing
451    /// codepoints not supported by said charset.
452    ///
453    /// Instead of disabling this, you may also consider setting [`.charset()`] to a charset that
454    /// is supported by your MySQL or MariaDB server version and compatible with UTF-8.
455    ///
456    /// [`.charset`]: Self::charset()
457    pub fn set_names(mut self, flag_val: bool) -> Self {
458        self.set_names = flag_val;
459        self
460    }
461
462    /// Sets the flag that enables or disables CLIENT_FOUND_ROWS,
463    /// to return the number of found (matched) rows, and not the number of changed rows.
464    ///
465    /// The default value is set to true.
466    pub fn found_rows(mut self, flag_val: bool) -> Self {
467        self.found_rows = flag_val;
468        self
469    }
470}
471
472impl MySqlConnectOptions {
473    /// Get the current host.
474    ///
475    /// # Example
476    ///
477    /// ```rust
478    /// # use sqlx_mysql::MySqlConnectOptions;
479    /// let options = MySqlConnectOptions::new()
480    ///     .host("127.0.0.1");
481    /// assert_eq!(options.get_host(), "127.0.0.1");
482    /// ```
483    pub fn get_host(&self) -> &str {
484        self.host.original()
485    }
486
487    /// Get the server's port.
488    ///
489    /// # Example
490    ///
491    /// ```rust
492    /// # use sqlx_mysql::MySqlConnectOptions;
493    /// let options = MySqlConnectOptions::new()
494    ///     .port(6543);
495    /// assert_eq!(options.get_port(), 6543);
496    /// ```
497    pub fn get_port(&self) -> u16 {
498        self.port
499    }
500
501    /// Get the socket path.
502    ///
503    /// # Example
504    ///
505    /// ```rust
506    /// # use sqlx_mysql::MySqlConnectOptions;
507    /// let options = MySqlConnectOptions::new()
508    ///     .socket("/tmp");
509    /// assert!(options.get_socket().is_some());
510    /// ```
511    pub fn get_socket(&self) -> Option<&PathBuf> {
512        self.socket.as_ref()
513    }
514
515    /// Get the current username.
516    ///
517    /// # Example
518    ///
519    /// ```rust
520    /// # use sqlx_mysql::MySqlConnectOptions;
521    /// let options = MySqlConnectOptions::new()
522    ///     .username("foo");
523    /// assert_eq!(options.get_username(), "foo");
524    /// ```
525    pub fn get_username(&self) -> &str {
526        &self.username
527    }
528
529    /// Get the current database name.
530    ///
531    /// # Example
532    ///
533    /// ```rust
534    /// # use sqlx_mysql::MySqlConnectOptions;
535    /// let options = MySqlConnectOptions::new()
536    ///     .database("postgres");
537    /// assert!(options.get_database().is_some());
538    /// ```
539    pub fn get_database(&self) -> Option<&str> {
540        self.database.as_deref()
541    }
542
543    /// Get the SSL mode.
544    ///
545    /// # Example
546    ///
547    /// ```rust
548    /// # use sqlx_mysql::{MySqlConnectOptions, MySqlSslMode};
549    /// let options = MySqlConnectOptions::new();
550    /// assert!(matches!(options.get_ssl_mode(), MySqlSslMode::Preferred));
551    /// ```
552    pub fn get_ssl_mode(&self) -> MySqlSslMode {
553        self.ssl_options.ssl_mode
554    }
555
556    /// Get the server charset.
557    ///
558    /// # Example
559    ///
560    /// ```rust
561    /// # use sqlx_mysql::MySqlConnectOptions;
562    /// let options = MySqlConnectOptions::new();
563    /// assert_eq!(options.get_charset(), "utf8mb4");
564    /// ```
565    pub fn get_charset(&self) -> &str {
566        &self.charset
567    }
568
569    /// Get the server collation.
570    ///
571    /// # Example
572    ///
573    /// ```rust
574    /// # use sqlx_mysql::MySqlConnectOptions;
575    /// let options = MySqlConnectOptions::new()
576    ///     .collation("collation");
577    /// assert!(options.get_collation().is_some());
578    /// ```
579    pub fn get_collation(&self) -> Option<&str> {
580        self.collation.as_deref()
581    }
582}
583
584#[cfg(test)]
585mod tests {
586    use super::MySqlConnectOptions;
587
588    #[test]
589    fn tls_server_name_is_stored() {
590        let opts = MySqlConnectOptions::new().tls_sni_servername("sni.example.com");
591        assert_eq!(opts.tls_sni_servername.as_deref(), Some("sni.example.com"));
592    }
593}