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};
const DETAILED: &str = "SELECT VARIABLE_NAME, SESSION_VALUE, GLOBAL_VALUE, DEFAULT_VALUE, \
VARIABLE_SCOPE FROM information_schema.SYSTEM_VARIABLES ORDER BY VARIABLE_NAME";
const PLAIN: &str = "SHOW GLOBAL VARIABLES";
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,
})
}
#[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
}
#[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()
}
fn differs(effective: &Value, factory: &Value) -> Option<bool> {
if factory.is_null() {
return None;
}
Some(text_of(Some(effective)) != text_of(Some(factory)))
}
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
}
#[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));
}
#[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));
}
#[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);
}
#[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);
}
#[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());
}
}