use super::handshake::{self, ServerFacts};
use super::OrFailure;
use crate::error::Result;
use mysql_async::{Conn, Opts};
#[derive(Debug)]
pub struct Session {
connection: Conn,
facts: ServerFacts,
}
impl Session {
pub async fn open(options: Opts) -> Result<Self> {
let mut connection = Conn::new(options)
.await
.map_err(|failed| super::map_driver_error_in(super::Channel::Opening, &failed))?;
let facts = handshake::probe(&mut connection).await?;
Ok(Self { connection, facts })
}
#[must_use]
pub const fn facts(&self) -> &ServerFacts {
&self.facts
}
pub const fn connection(&mut self) -> &mut Conn {
&mut self.connection
}
pub async fn close(self) -> Result<()> {
self.connection.disconnect().await.or_failure()
}
pub async fn close_after<T>(self, outcome: Result<T>) -> Result<T> {
combine(outcome, self.close().await)
}
}
fn combine<T>(work: Result<T>, closed: Result<()>) -> Result<T> {
match work {
Ok(value) => closed.map(|()| value),
Err(failure) => Err(failure),
}
}
#[cfg(test)]
mod tests {
use super::combine;
use crate::error::{Category, Failure, Result};
#[test]
fn the_work_failure_survives_a_clean_close() {
let work: Result<u8> = Err(Failure::conflict(
"conflict.deadlock",
"the change hit a deadlock",
));
let failure = combine(work, Ok(())).expect_err("the work failure must survive");
assert_eq!(failure.category(), Category::Conflict);
}
#[test]
fn a_close_failure_is_reported_when_the_work_went_well() {
let closed: Result<()> = Err(Failure::network(
"network.unreachable",
"the channel was lost",
));
assert_eq!(
combine(Ok(7_u8), closed)
.expect_err("the close failure must surface")
.code(),
"network.unreachable"
);
}
#[test]
fn a_failed_close_never_replaces_the_work_failure() {
let work: Result<u8> = Err(Failure::permission("permission.denied", "not allowed"));
let closed: Result<()> = Err(Failure::network("network.unreachable", "channel lost"));
assert_eq!(
combine(work, closed).expect_err("must fail").code(),
"permission.denied"
);
}
#[test]
fn a_clean_call_and_a_clean_close_return_the_value() {
assert_eq!(combine(Ok(7_u8), Ok(())).expect("clean"), 7);
}
}