mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Configuration variables, with the ones moved off the factory value marked.
//!
//! A bare list of variables answers the wrong question. What a caller
//! investigating odd behaviour needs is which of them somebody changed, so the
//! factory value is read alongside the value in force and the difference is
//! marked. When the server cannot say what the factory value was, the mark is
//! declared missing rather than guessed.

use super::{cell, fetch, matches_pattern, pairs, text_of, ServerSettings};
use crate::cli::server::PatternArgs;
use crate::error::{Failure, Result};
use crate::output::{Envelope, Gap, Row};
use mysql_async::{Conn, Params};
use serde_json::{json, Value};

/// The listing that carries the factory value beside the value in force.
///
/// Both scopes come from the same read, so the answer can say what the session
/// sees and what the whole server sees without a second round trip.
const DETAILED: &str = "SELECT VARIABLE_NAME, SESSION_VALUE, GLOBAL_VALUE, DEFAULT_VALUE, \
     VARIABLE_SCOPE FROM information_schema.SYSTEM_VARIABLES ORDER BY VARIABLE_NAME";

/// The listing every server of the family has, which knows no factory value.
const PLAIN: &str = "SHOW GLOBAL VARIABLES";

/// Lists the configuration variables in force.
///
/// # Errors
///
/// Returns an absence failure when the caller's pattern matches nothing, so a
/// pattern that found nothing is never mistaken for a server with nothing to
/// say, and the mapped driver failure when neither listing can be read.
pub async fn run(
    connection: &mut Conn,
    args: &PatternArgs,
    _settings: &ServerSettings,
) -> Result<Envelope> {
    let pattern = args.pattern.as_deref();

    let (rows, gap) = match fetch(connection, DETAILED, Params::Empty).await {
        Ok(detailed) => (detailed_rows(&detailed, pattern), None),
        Err(failure) if super::is_absent_structure(&failure) => {
            let plain = fetch(connection, PLAIN, Params::Empty).await?;
            (
                plain_rows(&plain, pattern),
                Some(Gap::new(
                    "changed_from_default",
                    "unsupported",
                    "this server does not publish the factory value of a variable, \
                     so no variable could be marked as changed"
                        .to_owned(),
                )),
            )
        }
        Err(failure) => return Err(failure),
    };

    if rows.is_empty() {
        return Err(nothing_matched(pattern));
    }

    let envelope = Envelope::new("server variables", json!({ "rows": rows }));
    Ok(match gap {
        Some(gap) => envelope.with_gap(gap),
        None => envelope,
    })
}

/// Shapes the listing that knows the factory value.
#[must_use]
pub fn detailed_rows(source: &[Row], pattern: Option<&str>) -> Vec<Row> {
    let mut rows = Vec::new();
    for row in source {
        let name = text_of(cell(row, "VARIABLE_NAME"));
        if pattern.is_some_and(|pattern| !matches_pattern(pattern, &name)) {
            continue;
        }
        let session = cell(row, "SESSION_VALUE").cloned().unwrap_or(Value::Null);
        let global = cell(row, "GLOBAL_VALUE").cloned().unwrap_or(Value::Null);
        let factory = cell(row, "DEFAULT_VALUE").cloned().unwrap_or(Value::Null);
        let effective = if session.is_null() {
            global.clone()
        } else {
            session.clone()
        };

        let mut shaped = Row::new();
        shaped.insert("name".to_owned(), json!(name));
        shaped.insert("value".to_owned(), effective.clone());
        shaped.insert("global_value".to_owned(), global);
        shaped.insert("session_value".to_owned(), session);
        shaped.insert("default_value".to_owned(), factory.clone());
        shaped.insert(
            "scope".to_owned(),
            cell(row, "VARIABLE_SCOPE").cloned().unwrap_or(Value::Null),
        );
        shaped.insert("changed".to_owned(), json!(differs(&effective, &factory)));
        rows.push(shaped);
    }
    rows
}

/// Shapes the listing that knows only the value in force.
#[must_use]
pub fn plain_rows(source: &[Row], pattern: Option<&str>) -> Vec<Row> {
    pairs(source)
        .into_iter()
        .filter(|(name, _)| pattern.is_none_or(|pattern| matches_pattern(pattern, name)))
        .map(|(name, value)| {
            let mut shaped = Row::new();
            shaped.insert("name".to_owned(), json!(name));
            shaped.insert("value".to_owned(), json!(value));
            shaped.insert("scope".to_owned(), json!("GLOBAL"));
            shaped.insert("changed".to_owned(), Value::Null);
            shaped
        })
        .collect()
}

/// Whether the value in force moved off the factory value.
///
/// A factory value the server does not know produces no mark at all, because
/// marking a variable unchanged on no evidence would be a claim, not a
/// reading.
fn differs(effective: &Value, factory: &Value) -> Option<bool> {
    if factory.is_null() {
        return None;
    }
    Some(text_of(Some(effective)) != text_of(Some(factory)))
}

/// The failure a pattern that matched nothing produces.
fn nothing_matched(pattern: Option<&str>) -> Failure {
    match pattern {
        Some(_) => Failure::absence(
            "absence.no_variable_matched",
            "no configuration variable matches the pattern given",
        )
        .with_hint("widen the pattern, or run without one to see every variable"),
        None => Failure::absence(
            "absence.no_variables",
            "the server published no configuration variables at all",
        )
        .with_hint("confirm the destination points at a server of the MariaDB family"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn detailed(name: &str, session: Value, global: &str, factory: Value) -> Row {
        let mut row = Row::new();
        row.insert("VARIABLE_NAME".to_owned(), json!(name));
        row.insert("SESSION_VALUE".to_owned(), session);
        row.insert("GLOBAL_VALUE".to_owned(), json!(global));
        row.insert("DEFAULT_VALUE".to_owned(), factory);
        row.insert("VARIABLE_SCOPE".to_owned(), json!("GLOBAL"));
        row
    }

    /// A variable moved off its factory value carries the mark, and one still
    /// on it does not.
    #[test]
    fn a_changed_variable_is_marked_and_an_untouched_one_is_not() {
        let source = vec![
            detailed("max_connections", Value::Null, "500", json!("151")),
            detailed("autocommit", Value::Null, "ON", json!("ON")),
        ];
        let rows = detailed_rows(&source, None);
        assert_eq!(rows[0]["changed"], json!(true));
        assert_eq!(rows[1]["changed"], json!(false));
    }

    /// The session value outranks the global one, because that is the value
    /// the caller's own statements will meet.
    #[test]
    fn the_session_value_is_the_value_in_force() {
        let source = vec![detailed(
            "sql_mode",
            json!("ANSI_QUOTES"),
            "STRICT_TRANS_TABLES",
            json!("STRICT_TRANS_TABLES"),
        )];
        let rows = detailed_rows(&source, None);
        assert_eq!(rows[0]["value"], json!("ANSI_QUOTES"));
        assert_eq!(rows[0]["changed"], json!(true));
    }

    /// A factory value the server does not know produces no mark at all.
    #[test]
    fn an_unknown_factory_value_produces_no_mark() {
        let source = vec![detailed("hostname", Value::Null, "db01", Value::Null)];
        let rows = detailed_rows(&source, None);
        assert_eq!(rows[0]["changed"], Value::Null);
    }

    /// The pattern narrows the listing the same way on both readings.
    #[test]
    fn the_pattern_narrows_both_listings() {
        let source = vec![
            detailed("max_connections", Value::Null, "500", json!("151")),
            detailed("autocommit", Value::Null, "ON", json!("ON")),
        ];
        assert_eq!(detailed_rows(&source, Some("max_%")).len(), 1);

        let mut plain = Row::new();
        plain.insert("Variable_name".to_owned(), json!("max_connections"));
        plain.insert("Value".to_owned(), json!("500"));
        assert_eq!(plain_rows(&[plain.clone()], Some("max_%")).len(), 1);
        assert_eq!(plain_rows(&[plain], Some("min_%")).len(), 0);
    }

    /// A pattern that matched nothing is an absence, so the caller knows the
    /// pattern was wrong rather than the server empty.
    #[test]
    fn a_pattern_matching_nothing_is_an_absence() {
        let failure = nothing_matched(Some("absent_%"));
        assert_eq!(failure.exit_number().code(), 8);
        assert!(failure.hint().is_some());
    }
}