use crate::connection::ConnectOptions;
use crate::error::Error;
use crate::executor::Executor;
use crate::{MySqlConnectOptions, MySqlConnection};
use log::LevelFilter;
use sqlx_core::sql_str::AssertSqlSafe;
use sqlx_core::Url;
use std::time::Duration;
impl ConnectOptions for MySqlConnectOptions {
type Connection = MySqlConnection;
fn from_url(url: &Url) -> Result<Self, Error> {
Self::parse_from_url(url)
}
fn to_url_lossy(&self) -> Url {
self.build_url()
}
async fn connect(&self) -> Result<Self::Connection, Error>
where
Self::Connection: Sized,
{
let mut conn = MySqlConnection::establish(self).await?;
if let Some(statement) = self.connect_init_statement() {
conn.execute(AssertSqlSafe(statement)).await?;
}
Ok(conn)
}
fn log_statements(mut self, level: LevelFilter) -> Self {
self.log_settings.log_statements(level);
self
}
fn log_slow_statements(mut self, level: LevelFilter, duration: Duration) -> Self {
self.log_settings.log_slow_statements(level, duration);
self
}
}
impl MySqlConnectOptions {
fn connect_init_statement(&self) -> Option<String> {
let mut sql_mode = Vec::new();
if self.pipes_as_concat {
sql_mode.push(r#"PIPES_AS_CONCAT"#);
}
if self.no_engine_substitution {
sql_mode.push(r#"NO_ENGINE_SUBSTITUTION"#);
}
let mut options = Vec::new();
if !sql_mode.is_empty() {
options.push(format!(
r#"sql_mode=(SELECT CONCAT(@@sql_mode, ',{}'))"#,
sql_mode.join(",")
));
}
if let Some(timezone) = &self.timezone {
options.push(format!("time_zone={}", quote_string_literal(timezone)));
}
if self.set_names {
let set_names = if let Some(collation) = &self.collation {
format!(
"NAMES {} COLLATE {}",
quote_string_literal(&self.charset),
quote_string_literal(collation),
)
} else {
format!("NAMES {}", quote_string_literal(&self.charset))
};
options.push(set_names);
}
if options.is_empty() {
None
} else {
Some(format!(r#"SET {};"#, options.join(",")))
}
}
}
fn quote_string_literal(value: &str) -> String {
let mut quoted = String::with_capacity(value.len() + 2);
quoted.push('\'');
for ch in value.chars() {
match ch {
'\\' => quoted.push_str(r#"\\"#),
'\'' => quoted.push_str("''"),
_ => quoted.push(ch),
}
}
quoted.push('\'');
quoted
}
#[cfg(test)]
mod tests {
use super::*;
use crate::MySqlConnectOptions;
use std::str::FromStr;
fn statement_for(url: &str) -> String {
MySqlConnectOptions::from_str(url)
.expect("valid URL")
.connect_init_statement()
.expect("connect-time SET statement")
}
#[test]
fn init_statement_quotes_charset_and_collation() {
let stmt = statement_for("mysql://user:password@localhost/database");
assert_eq!(
stmt,
"SET sql_mode=(SELECT CONCAT(@@sql_mode, ',PIPES_AS_CONCAT,NO_ENGINE_SUBSTITUTION')),\
time_zone='+00:00',NAMES 'utf8mb4';"
);
}
#[test]
fn init_statement_quotes_time_zone() {
let stmt = statement_for("mysql://user:password@localhost/database?timezone=%2B08:00");
assert!(
stmt.contains("time_zone='+08:00'"),
"unexpected statement: {stmt}"
);
}
#[test]
fn init_statement_quotes_explicit_collation() {
let stmt = statement_for("mysql://user:password@localhost/database?collation=utf8mb4_bin");
assert!(
stmt.contains("NAMES 'utf8mb4' COLLATE 'utf8mb4_bin'"),
"unexpected statement: {stmt}"
);
}
#[test]
fn init_statement_neutralizes_time_zone_injection() {
let stmt = statement_for(
"mysql://user:password@localhost/database?timezone=%27%3BSELECT+SLEEP%285%29%3B--%20",
);
assert!(
!stmt.contains("time_zone='';"),
"injection not neutralized: {stmt}"
);
assert!(
stmt.contains("time_zone=''';SELECT SLEEP(5);-- '"),
"unexpected statement: {stmt}"
);
}
#[test]
fn init_statement_neutralizes_charset_injection() {
let stmt = statement_for(
"mysql://user:password@localhost/database?charset=utf8mb4%27%3BSELECT+SLEEP%285%29%3B--%20",
);
assert!(
stmt.contains("NAMES 'utf8mb4'';SELECT SLEEP(5);-- '"),
"unexpected statement: {stmt}"
);
}
#[test]
fn init_statement_neutralizes_collation_injection() {
let stmt = statement_for(
"mysql://user:password@localhost/database?collation=x%27%3BSELECT+SLEEP%285%29%3B--%20",
);
assert!(
stmt.contains("COLLATE 'x'';SELECT SLEEP(5);-- '"),
"unexpected statement: {stmt}"
);
}
#[test]
fn init_statement_escapes_backslashes() {
assert_eq!(quote_string_literal("a\\b"), "'a\\\\b'");
assert_eq!(quote_string_literal("a\\'b"), "'a\\\\''b'");
assert_eq!(quote_string_literal("plain"), "'plain'");
assert_eq!(quote_string_literal("it's"), "'it''s'");
}
}