mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The one session an invocation gets.
//!
//! The process is born, opens one connection, works and dies. There is no pool,
//! because a pool exists to hand a connection to the *next* caller and there is
//! no next caller: the process ends. A pool here would only add a background
//! task that must be shut down before the process may exit.
//!
//! The connection is closed explicitly rather than left to the value being
//! dropped, because dropping an asynchronous connection cannot wait for the
//! server to be told, and a server told nothing keeps the session until its own
//! idle limit expires.

use super::handshake::{self, ServerFacts};
use super::OrFailure;
use crate::error::Result;
use mysql_async::{Conn, Opts};

/// An open connection together with what the server said about itself.
#[derive(Debug)]
pub struct Session {
    connection: Conn,
    facts: ServerFacts,
}

impl Session {
    /// Opens a connection and reads the server's own account of itself.
    ///
    /// The adjustments the destination declares are already part of the options
    /// and are applied by the driver as the connection opens, so they are in
    /// force before this function returns and before any caller statement runs.
    /// Automatic confirmation is among them and is switched off, which is what
    /// keeps a read from ever persisting anything.
    ///
    /// # Errors
    ///
    /// Returns the mapped driver failure when the server cannot be reached, the
    /// credential is refused or an adjustment is rejected.
    pub async fn open(options: Opts) -> Result<Self> {
        // Named as an opening channel, because this is one of the two places
        // where nothing has been agreed yet and the bytes stopping really does
        // mean the server was never reached.
        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 })
    }

    /// What the server said about itself when this session opened.
    #[must_use]
    pub const fn facts(&self) -> &ServerFacts {
        &self.facts
    }

    /// The open connection, for the command that needs to speak to the server.
    pub const fn connection(&mut self) -> &mut Conn {
        &mut self.connection
    }

    /// Closes the session, telling the server the caller is finished.
    ///
    /// Consumes the session, so nothing can be sent afterwards.
    ///
    /// # Errors
    ///
    /// Returns the mapped driver failure when the server could not be told.
    pub async fn close(self) -> Result<()> {
        self.connection.disconnect().await.or_failure()
    }

    /// Closes the session, keeping the outcome of the work that came first.
    ///
    /// A failure closing the channel must not hide the failure that made the
    /// caller stop, and a successful close must not turn a failed call into a
    /// successful one. The outcome of the work wins in both directions.
    ///
    /// # Errors
    ///
    /// Returns the failure of the work when there was one, and the failure of
    /// closing the channel only when the work itself succeeded.
    pub async fn close_after<T>(self, outcome: Result<T>) -> Result<T> {
        combine(outcome, self.close().await)
    }
}

/// Decides which of two outcomes the caller is told about.
///
/// Kept apart from the round trip so the rule itself is provable without a
/// server, since it is the rule and not the network that decides.
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};

    /// A failure during the work survives a clean close, so the caller is told
    /// why the work stopped and not that everything went well.
    #[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);
    }

    /// A failure closing the channel is reported when the work itself went
    /// well, so a session the server was never told about is not silent.
    #[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"
        );
    }

    /// A failed close never hides a failed call by replacing its cause.
    #[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"
        );
    }

    /// A clean call and a clean close hand the value straight through.
    #[test]
    fn a_clean_call_and_a_clean_close_return_the_value() {
        assert_eq!(combine(Ok(7_u8), Ok(())).expect("clean"), 7);
    }
}