Skip to content
This repository has been archived by the owner on Apr 25, 2023. It is now read-only.

Commit

Permalink
Updating to the latest mysql_async (#433)
Browse files Browse the repository at this point in the history
  • Loading branch information
Julius de Bruijn authored Feb 20, 2023
1 parent 2e6305d commit 2aa9ac0
Show file tree
Hide file tree
Showing 33 changed files with 469 additions and 478 deletions.
5 changes: 5 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ jobs:
with:
components: clippy
override: true
toolchain: stable
- name: Install dependencies
run: sudo apt install -y openssl libkrb5-dev
- uses: actions-rs/clippy-check@v1
Expand All @@ -31,6 +32,7 @@ jobs:
with:
components: rustfmt
override: true
toolchain: stable
- uses: mbrobbel/rustfmt-check@master
with:
token: ${{ secrets.GITHUB_TOKEN }}
Expand Down Expand Up @@ -64,6 +66,9 @@ jobs:
- uses: actions/checkout@v2

- uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true

- uses: actions/cache@v2
with:
Expand Down
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ all = [
"serde-support",
"sqlite",
"uuid",
"bigdecimal"
"bigdecimal",
]

vendored-openssl = [
"postgres-native-tls/vendored-openssl",
"mysql_async/vendored-openssl"
"mysql_async/vendored-openssl",
]

postgresql = [
Expand Down
2 changes: 1 addition & 1 deletion src/ast/compare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ impl<'a> Compare<'a> {
let mut cols = row.into_columns();

// The name of the CTE in the query
let ident = format!("cte_{}", level);
let ident = format!("cte_{level}");

let (select, ctes) = select.convert_tuple_selects_to_ctes(level);

Expand Down
54 changes: 27 additions & 27 deletions src/ast/values.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ impl<'a> fmt::Display for Params<'a> {

write!(f, "[")?;
for (i, val) in self.0.iter().enumerate() {
write!(f, "{}", val)?;
write!(f, "{val}")?;

if i < (len - 1) {
write!(f, ",")?;
Expand All @@ -110,41 +110,41 @@ impl<'a> fmt::Display for Params<'a> {
impl<'a> fmt::Display for Value<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let res = match self {
Value::Int32(val) => val.map(|v| write!(f, "{}", v)),
Value::Int64(val) => val.map(|v| write!(f, "{}", v)),
Value::Float(val) => val.map(|v| write!(f, "{}", v)),
Value::Double(val) => val.map(|v| write!(f, "{}", v)),
Value::Text(val) => val.as_ref().map(|v| write!(f, "\"{}\"", v)),
Value::Int32(val) => val.map(|v| write!(f, "{v}")),
Value::Int64(val) => val.map(|v| write!(f, "{v}")),
Value::Float(val) => val.map(|v| write!(f, "{v}")),
Value::Double(val) => val.map(|v| write!(f, "{v}")),
Value::Text(val) => val.as_ref().map(|v| write!(f, "\"{v}\"")),
Value::Bytes(val) => val.as_ref().map(|v| write!(f, "<{} bytes blob>", v.len())),
Value::Enum(val) => val.as_ref().map(|v| write!(f, "\"{}\"", v)),
Value::Boolean(val) => val.map(|v| write!(f, "{}", v)),
Value::Char(val) => val.map(|v| write!(f, "'{}'", v)),
Value::Enum(val) => val.as_ref().map(|v| write!(f, "\"{v}\"")),
Value::Boolean(val) => val.map(|v| write!(f, "{v}")),
Value::Char(val) => val.map(|v| write!(f, "'{v}'")),
Value::Array(vals) => vals.as_ref().map(|vals| {
let len = vals.len();

write!(f, "[")?;
for (i, val) in vals.iter().enumerate() {
write!(f, "{}", val)?;
write!(f, "{val}")?;

if i < (len - 1) {
write!(f, ",")?;
}
}
write!(f, "]")
}),
Value::Xml(val) => val.as_ref().map(|v| write!(f, "{}", v)),
Value::Xml(val) => val.as_ref().map(|v| write!(f, "{v}")),
#[cfg(feature = "bigdecimal")]
Value::Numeric(val) => val.as_ref().map(|v| write!(f, "{}", v)),
Value::Numeric(val) => val.as_ref().map(|v| write!(f, "{v}")),
#[cfg(feature = "json")]
Value::Json(val) => val.as_ref().map(|v| write!(f, "{}", v)),
Value::Json(val) => val.as_ref().map(|v| write!(f, "{v}")),
#[cfg(feature = "uuid")]
Value::Uuid(val) => val.map(|v| write!(f, "\"{}\"", v)),
Value::Uuid(val) => val.map(|v| write!(f, "\"{v}\"")),
#[cfg(feature = "chrono")]
Value::DateTime(val) => val.map(|v| write!(f, "\"{}\"", v)),
Value::DateTime(val) => val.map(|v| write!(f, "\"{v}\"")),
#[cfg(feature = "chrono")]
Value::Date(val) => val.map(|v| write!(f, "\"{}\"", v)),
Value::Date(val) => val.map(|v| write!(f, "\"{v}\"")),
#[cfg(feature = "chrono")]
Value::Time(val) => val.map(|v| write!(f, "\"{}\"", v)),
Value::Time(val) => val.map(|v| write!(f, "\"{v}\"")),
};

match res {
Expand All @@ -170,7 +170,7 @@ impl<'a> From<Value<'a>> for serde_json::Value {
None => serde_json::Value::Null,
}),
Value::Text(cow) => cow.map(|cow| serde_json::Value::String(cow.into_owned())),
Value::Bytes(bytes) => bytes.map(|bytes| serde_json::Value::String(base64::encode(&bytes))),
Value::Bytes(bytes) => bytes.map(|bytes| serde_json::Value::String(base64::encode(bytes))),
Value::Enum(cow) => cow.map(|cow| serde_json::Value::String(cow.into_owned())),
Value::Boolean(b) => b.map(serde_json::Value::Bool),
Value::Char(c) => c.map(|c| {
Expand All @@ -193,9 +193,9 @@ impl<'a> From<Value<'a>> for serde_json::Value {
#[cfg(feature = "chrono")]
Value::DateTime(dt) => dt.map(|dt| serde_json::Value::String(dt.to_rfc3339())),
#[cfg(feature = "chrono")]
Value::Date(date) => date.map(|date| serde_json::Value::String(format!("{}", date))),
Value::Date(date) => date.map(|date| serde_json::Value::String(format!("{date}"))),
#[cfg(feature = "chrono")]
Value::Time(time) => time.map(|time| serde_json::Value::String(format!("{}", time))),
Value::Time(time) => time.map(|time| serde_json::Value::String(format!("{time}"))),
};

match res {
Expand Down Expand Up @@ -427,7 +427,7 @@ impl<'a> Value<'a> {
pub fn to_bytes(&self) -> Option<Vec<u8>> {
match self {
Value::Text(Some(cow)) => Some(cow.to_string().into_bytes()),
Value::Bytes(Some(cow)) => Some(cow.to_owned().into()),
Value::Bytes(Some(cow)) => Some(cow.to_vec()),
_ => None,
}
}
Expand Down Expand Up @@ -785,7 +785,7 @@ impl<'a> TryFrom<&Value<'a>> for Option<std::net::IpAddr> {
v if v.is_null() => Ok(None),
v => {
let kind =
ErrorKind::conversion(format!("Couldn't convert value of type `{:?}` to std::net::IpAddr.", v));
ErrorKind::conversion(format!("Couldn't convert value of type `{v:?}` to std::net::IpAddr."));

Err(Error::builder(kind).build())
}
Expand Down Expand Up @@ -818,7 +818,7 @@ impl<'a> TryFrom<&Value<'a>> for Option<uuid::Uuid> {
}
v if v.is_null() => Ok(None),
v => {
let kind = ErrorKind::conversion(format!("Couldn't convert value of type `{:?}` to uuid::Uuid.", v));
let kind = ErrorKind::conversion(format!("Couldn't convert value of type `{v:?}` to uuid::Uuid."));

Err(Error::builder(kind).build())
}
Expand Down Expand Up @@ -974,7 +974,7 @@ mod tests {
let dt: DateTime<Utc> = DateTime::from_str("2019-07-27T05:30:30Z").expect("failed while parsing date");
let pv = Value::datetime(dt);

assert_eq!(format!("{}", pv), "\"2019-07-27 05:30:30 UTC\"");
assert_eq!(format!("{pv}"), "\"2019-07-27 05:30:30 UTC\"");
}

#[test]
Expand All @@ -983,7 +983,7 @@ mod tests {
let date = NaiveDate::from_ymd_opt(2022, 8, 11).unwrap();
let pv = Value::date(date);

assert_eq!(format!("{}", pv), "\"2022-08-11\"");
assert_eq!(format!("{pv}"), "\"2022-08-11\"");
}

#[test]
Expand All @@ -992,7 +992,7 @@ mod tests {
let time = NaiveTime::from_hms_opt(16, 17, 00).unwrap();
let pv = Value::time(time);

assert_eq!(format!("{}", pv), "\"16:17:00\"");
assert_eq!(format!("{pv}"), "\"16:17:00\"");
}

#[test]
Expand All @@ -1001,6 +1001,6 @@ mod tests {
let id = Uuid::from_str("67e5504410b1426f9247bb680e5fe0c8").unwrap();
let pv = Value::uuid(id);

assert_eq!(format!("{}", pv), "\"67e55044-10b1-426f-9247-bb680e5fe0c8\"");
assert_eq!(format!("{pv}"), "\"67e55044-10b1-426f-9247-bb680e5fe0c8\"");
}
}
2 changes: 1 addition & 1 deletion src/connector/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ where
trace_query(query, params, result, start);
}

histogram!(format!("{}.query.time", tag), start.elapsed());
histogram!(format!("{tag}.query.time"), start.elapsed());
histogram!("prisma_datasource_queries_duration_histogram_ms", start.elapsed());
increment_counter!("prisma_datasource_queries_total");

Expand Down
10 changes: 5 additions & 5 deletions src/connector/mssql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ impl Mssql {
};

if let Some(isolation) = this.url.transaction_isolation_level() {
this.raw_cmd(&format!("SET TRANSACTION ISOLATION LEVEL {}", isolation))
this.raw_cmd(&format!("SET TRANSACTION ISOLATION LEVEL {isolation}"))
.await?;
};

Expand Down Expand Up @@ -435,7 +435,7 @@ impl Queryable for Mssql {
}

async fn set_tx_isolation_level(&self, isolation_level: IsolationLevel) -> crate::Result<()> {
self.raw_cmd(&format!("SET TRANSACTION ISOLATION LEVEL {}", isolation_level))
self.raw_cmd(&format!("SET TRANSACTION ISOLATION LEVEL {isolation_level}"))
.await?;

Ok(())
Expand Down Expand Up @@ -465,15 +465,15 @@ impl MssqlUrl {
if input.starts_with("jdbc:sqlserver") {
input.into()
} else {
format!("jdbc:{}", input)
format!("jdbc:{input}")
}
}

fn parse_query_params(input: &str) -> crate::Result<MssqlQueryParams> {
let mut conn = JdbcString::from_str(&Self::with_jdbc_prefix(input))?;

let host = conn.server_name().map(|server_name| match conn.instance_name() {
Some(instance_name) => format!(r#"{}\{}"#, server_name, instance_name),
Some(instance_name) => format!(r#"{server_name}\{instance_name}"#),
None => server_name.to_string(),
});

Expand All @@ -495,7 +495,7 @@ impl MssqlUrl {
.or_else(|| props.remove("isolation_level"))
.map(|level| {
IsolationLevel::from_str(&level).map_err(|_| {
let kind = ErrorKind::database_url_is_invalid(format!("Invalid isolation level `{}`", level));
let kind = ErrorKind::database_url_is_invalid(format!("Invalid isolation level `{level}`"));
Error::builder(kind).build()
})
})
Expand Down
2 changes: 1 addition & 1 deletion src/connector/mssql/conversion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ impl<'a> IntoSql<'a> for &'a Value<'a> {
Value::Bytes(val) => val.as_deref().into_sql(),
Value::Enum(val) => val.as_deref().into_sql(),
Value::Boolean(val) => val.into_sql(),
Value::Char(val) => val.as_ref().map(|val| format!("{}", val)).into_sql(),
Value::Char(val) => val.as_ref().map(|val| format!("{val}")).into_sql(),
Value::Xml(val) => val.as_deref().into_sql(),
Value::Array(_) => panic!("Arrays are not supported on SQL Server."),
#[cfg(feature = "bigdecimal")]
Expand Down
3 changes: 1 addition & 2 deletions src/connector/mssql/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ impl From<tiberius::error::Error> for Error {
e @ tiberius::error::Error::Io { .. } => Error::builder(ErrorKind::ConnectionError(e.into())).build(),
tiberius::error::Error::Tls(message) => {
let message = format!(
"The TLS settings didn't allow the connection to be established. Please review your connection string. (error: {})",
message
"The TLS settings didn't allow the connection to be established. Please review your connection string. (error: {message})"
);

Error::builder(ErrorKind::TlsError { message }).build()
Expand Down
33 changes: 27 additions & 6 deletions src/connector/mysql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use percent_encoding::percent_decode;
use std::{
borrow::Cow,
future::Future,
path::Path,
path::{Path, PathBuf},
sync::atomic::{AtomicBool, Ordering},
time::Duration,
};
Expand Down Expand Up @@ -163,6 +163,7 @@ impl MysqlUrl {
let mut max_idle_connection_lifetime = Some(Duration::from_secs(300));
let mut prefer_socket = None;
let mut statement_cache_size = 100;
let mut identity: Option<(Option<PathBuf>, Option<String>)> = None;

for (k, v) in url.query_pairs() {
match k.as_ref() {
Expand All @@ -184,14 +185,22 @@ impl MysqlUrl {
}
"sslidentity" => {
use_ssl = true;
ssl_opts = ssl_opts.with_pkcs12_path(Some(Path::new(&*v).to_path_buf()));

identity = match identity {
Some((_, pw)) => Some((Some(Path::new(&*v).to_path_buf()), pw)),
None => Some((Some(Path::new(&*v).to_path_buf()), None)),
};
}
"sslpassword" => {
use_ssl = true;
ssl_opts = ssl_opts.with_password(Some(v.to_string()));

identity = match identity {
Some((path, _)) => Some((path, Some(v.to_string()))),
None => Some((None, Some(v.to_string()))),
};
}
"socket" => {
socket = Some(v.replace('(', "").replace(')', ""));
socket = Some(v.replace(['(', ')'], ""));
}
"socket_timeout" => {
let as_int = v
Expand Down Expand Up @@ -268,6 +277,18 @@ impl MysqlUrl {
};
}

ssl_opts = match identity {
Some((Some(path), Some(pw))) => {
let identity = mysql_async::ClientIdentity::new(path).with_password(pw);
ssl_opts.with_client_identity(Some(identity))
}
Some((Some(path), None)) => {
let identity = mysql_async::ClientIdentity::new(path);
ssl_opts.with_client_identity(Some(identity))
}
_ => ssl_opts,
};

Ok(MysqlUrlQueryParams {
ssl_opts,
connection_limit,
Expand Down Expand Up @@ -542,7 +563,7 @@ impl Queryable for Mysql {
return Err(Error::builder(ErrorKind::invalid_isolation_level(&isolation_level)).build());
}

self.raw_cmd(&format!("SET TRANSACTION ISOLATION LEVEL {}", isolation_level))
self.raw_cmd(&format!("SET TRANSACTION ISOLATION LEVEL {isolation_level}"))
.await?;

Ok(())
Expand Down Expand Up @@ -598,7 +619,7 @@ mod tests {

#[tokio::test]
async fn should_map_nonexisting_database_error() {
let mut url = Url::parse(&*CONN_STR).unwrap();
let mut url = Url::parse(&CONN_STR).unwrap();
url.set_username("root").unwrap();
url.set_path("/this_does_not_exist");

Expand Down
9 changes: 3 additions & 6 deletions src/connector/mysql/conversion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ pub fn conv_params(params: &[Value<'_>]) -> crate::Result<my::Params> {
Value::Int64(i) => i.map(my::Value::Int),
Value::Float(f) => f.map(my::Value::Float),
Value::Double(f) => f.map(my::Value::Double),
Value::Text(s) => s.clone().map(|s| my::Value::Bytes((&*s).as_bytes().to_vec())),
Value::Text(s) => s.clone().map(|s| my::Value::Bytes((*s).as_bytes().to_vec())),
Value::Bytes(bytes) => bytes.clone().map(|bytes| my::Value::Bytes(bytes.into_owned())),
Value::Enum(s) => s.clone().map(|s| my::Value::Bytes((&*s).as_bytes().to_vec())),
Value::Enum(s) => s.clone().map(|s| my::Value::Bytes((*s).as_bytes().to_vec())),
Value::Boolean(b) => b.map(|b| my::Value::Int(b as i64)),
Value::Char(c) => c.map(|c| my::Value::Bytes(vec![c as u8])),
Value::Xml(s) => s.as_ref().map(|s| my::Value::Bytes((s).as_bytes().to_vec())),
Expand Down Expand Up @@ -331,10 +331,7 @@ impl TakeRow for my::Row {
#[cfg(feature = "json")]
t if t.is_json() => Value::Json(None),
typ => {
let msg = format!(
"Value of type {:?} is not supported with the current configuration",
typ
);
let msg = format!("Value of type {typ:?} is not supported with the current configuration");

let kind = ErrorKind::conversion(msg);
return Err(Error::builder(kind).build());
Expand Down
Loading

0 comments on commit 2aa9ac0

Please sign in to comment.