sqlx_mysql/options/
connect.rs1use crate::connection::ConnectOptions;
2use crate::error::Error;
3use crate::executor::Executor;
4use crate::{MySqlConnectOptions, MySqlConnection};
5use log::LevelFilter;
6use sqlx_core::sql_str::AssertSqlSafe;
7use sqlx_core::Url;
8use std::time::Duration;
9
10impl ConnectOptions for MySqlConnectOptions {
11 type Connection = MySqlConnection;
12
13 fn from_url(url: &Url) -> Result<Self, Error> {
14 Self::parse_from_url(url)
15 }
16
17 fn to_url_lossy(&self) -> Url {
18 self.build_url()
19 }
20
21 async fn connect(&self) -> Result<Self::Connection, Error>
22 where
23 Self::Connection: Sized,
24 {
25 let mut conn = MySqlConnection::establish(self).await?;
26
27 if let Some(statement) = self.connect_init_statement() {
31 conn.execute(AssertSqlSafe(statement)).await?;
32 }
33
34 Ok(conn)
35 }
36
37 fn log_statements(mut self, level: LevelFilter) -> Self {
38 self.log_settings.log_statements(level);
39 self
40 }
41
42 fn log_slow_statements(mut self, level: LevelFilter, duration: Duration) -> Self {
43 self.log_settings.log_slow_statements(level, duration);
44 self
45 }
46}
47
48impl MySqlConnectOptions {
49 fn connect_init_statement(&self) -> Option<String> {
54 let mut sql_mode = Vec::new();
77 if self.pipes_as_concat {
78 sql_mode.push(r#"PIPES_AS_CONCAT"#);
79 }
80 if self.no_engine_substitution {
81 sql_mode.push(r#"NO_ENGINE_SUBSTITUTION"#);
82 }
83
84 let mut options = Vec::new();
85 if !sql_mode.is_empty() {
86 options.push(format!(
87 r#"sql_mode=(SELECT CONCAT(@@sql_mode, ',{}'))"#,
88 sql_mode.join(",")
89 ));
90 }
91
92 if let Some(timezone) = &self.timezone {
93 options.push(format!("time_zone={}", quote_string_literal(timezone)));
94 }
95
96 if self.set_names {
97 let set_names = if let Some(collation) = &self.collation {
100 format!(
101 "NAMES {} COLLATE {}",
102 quote_string_literal(&self.charset),
103 quote_string_literal(collation),
104 )
105 } else {
106 format!("NAMES {}", quote_string_literal(&self.charset))
109 };
110
111 options.push(set_names);
112 }
113
114 if options.is_empty() {
115 None
116 } else {
117 Some(format!(r#"SET {};"#, options.join(",")))
118 }
119 }
120}
121
122fn quote_string_literal(value: &str) -> String {
135 let mut quoted = String::with_capacity(value.len() + 2);
136 quoted.push('\'');
137 for ch in value.chars() {
138 match ch {
139 '\\' => quoted.push_str(r#"\\"#),
140 '\'' => quoted.push_str("''"),
141 _ => quoted.push(ch),
142 }
143 }
144 quoted.push('\'');
145 quoted
146}
147
148#[cfg(test)]
149mod tests {
150 use super::*;
151 use crate::MySqlConnectOptions;
152 use std::str::FromStr;
153
154 fn statement_for(url: &str) -> String {
155 MySqlConnectOptions::from_str(url)
156 .expect("valid URL")
157 .connect_init_statement()
158 .expect("connect-time SET statement")
159 }
160
161 #[test]
162 fn init_statement_quotes_charset_and_collation() {
163 let stmt = statement_for("mysql://user:password@localhost/database");
164
165 assert_eq!(
168 stmt,
169 "SET sql_mode=(SELECT CONCAT(@@sql_mode, ',PIPES_AS_CONCAT,NO_ENGINE_SUBSTITUTION')),\
170 time_zone='+00:00',NAMES 'utf8mb4';"
171 );
172 }
173
174 #[test]
175 fn init_statement_quotes_time_zone() {
176 let stmt = statement_for("mysql://user:password@localhost/database?timezone=%2B08:00");
177
178 assert!(
179 stmt.contains("time_zone='+08:00'"),
180 "unexpected statement: {stmt}"
181 );
182 }
183
184 #[test]
185 fn init_statement_quotes_explicit_collation() {
186 let stmt = statement_for("mysql://user:password@localhost/database?collation=utf8mb4_bin");
187
188 assert!(
189 stmt.contains("NAMES 'utf8mb4' COLLATE 'utf8mb4_bin'"),
190 "unexpected statement: {stmt}"
191 );
192 }
193
194 #[test]
195 fn init_statement_neutralizes_time_zone_injection() {
196 let stmt = statement_for(
200 "mysql://user:password@localhost/database?timezone=%27%3BSELECT+SLEEP%285%29%3B--%20",
201 );
202
203 assert!(
205 !stmt.contains("time_zone='';"),
206 "injection not neutralized: {stmt}"
207 );
208 assert!(
210 stmt.contains("time_zone=''';SELECT SLEEP(5);-- '"),
211 "unexpected statement: {stmt}"
212 );
213 }
214
215 #[test]
216 fn init_statement_neutralizes_charset_injection() {
217 let stmt = statement_for(
219 "mysql://user:password@localhost/database?charset=utf8mb4%27%3BSELECT+SLEEP%285%29%3B--%20",
220 );
221
222 assert!(
223 stmt.contains("NAMES 'utf8mb4'';SELECT SLEEP(5);-- '"),
224 "unexpected statement: {stmt}"
225 );
226 }
227
228 #[test]
229 fn init_statement_neutralizes_collation_injection() {
230 let stmt = statement_for(
231 "mysql://user:password@localhost/database?collation=x%27%3BSELECT+SLEEP%285%29%3B--%20",
232 );
233
234 assert!(
235 stmt.contains("COLLATE 'x'';SELECT SLEEP(5);-- '"),
236 "unexpected statement: {stmt}"
237 );
238 }
239
240 #[test]
241 fn init_statement_escapes_backslashes() {
242 assert_eq!(quote_string_literal("a\\b"), "'a\\\\b'");
245 assert_eq!(quote_string_literal("a\\'b"), "'a\\\\''b'");
246 assert_eq!(quote_string_literal("plain"), "'plain'");
247 assert_eq!(quote_string_literal("it's"), "'it''s'");
248 }
249}