mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The variant of this destination and which optional features it really has.
//!
//! Every feature here is optional: it exists on some servers of the family and
//! not on others. A caller told plainly that a feature is absent stops before
//! asking for it, instead of discovering the absence through a server error
//! that says nothing about what to do next.
//!
//! Nothing is asked of the server here. Everything was read once when the
//! connection opened, so this command costs no round trip at all.

use crate::conn::handshake::ServerFacts;
use crate::output::{Envelope, Row};
use serde_json::{json, Value};

/// The release each optional feature first appeared in on this family.
///
/// A version comparison is used rather than a probe of each feature, because a
/// probe would cost one round trip per feature on a tool that lives for a
/// single call.
const SINCE: [(&str, u16, u16, &str); 4] = [
    (
        "system_versioning",
        10,
        3,
        "tables can keep a version history",
    ),
    (
        "sequences",
        10,
        3,
        "number generators exist as objects of their own",
    ),
    (
        "roles",
        10,
        0,
        "rights can be granted to a role rather than a user",
    ),
    (
        "checked_documents",
        10,
        4,
        "structured documents are checked rather than stored as plain text",
    ),
];

/// Declares the variant and the optional features of this destination.
#[must_use]
pub fn run(facts: &ServerFacts) -> Envelope {
    Envelope::new(
        "server capabilities",
        json!({
            "variant": variant(facts),
            "version": facts.version,
            "version_parts": [
                facts.version_parts.0,
                facts.version_parts.1,
                facts.version_parts.2,
            ],
            "meets_minimum_version": facts.meets_minimum_version,
            "rows": features(facts),
        }),
    )
}

/// The name of the family this destination belongs to.
#[must_use]
pub fn variant(facts: &ServerFacts) -> &'static str {
    if facts.is_mariadb {
        "mariadb"
    } else {
        "other"
    }
}

/// One row per optional feature, each marked present or absent.
///
/// Every feature always appears, present or not, so a caller reading the
/// answer learns the whole set rather than only what happens to be there.
#[must_use]
pub fn features(facts: &ServerFacts) -> Vec<Row> {
    SINCE
        .iter()
        .map(|(name, major, minor, about)| {
            let present = facts.is_mariadb && at_least(facts.version_parts, *major, *minor);
            let mut row = Row::new();
            row.insert("feature".to_owned(), json!(name));
            row.insert("present".to_owned(), json!(present));
            row.insert("about".to_owned(), json!(about));
            row.insert("since".to_owned(), json!(format!("{major}.{minor}")));
            row.insert(
                "absent_because".to_owned(),
                reason(facts.is_mariadb, present, *major, *minor),
            );
            row
        })
        .collect()
}

/// Why a feature is absent, when it is.
fn reason(is_mariadb: bool, present: bool, major: u16, minor: u16) -> Value {
    if present {
        return Value::Null;
    }
    if is_mariadb {
        json!(format!(
            "this feature needs release {major}.{minor} or newer"
        ))
    } else {
        json!("this feature belongs to MariaDB and this destination is another server")
    }
}

/// Whether these version parts reach the given release.
const fn at_least(parts: (u16, u16, u16), major: u16, minor: u16) -> bool {
    parts.0 > major || (parts.0 == major && parts.1 >= minor)
}

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

    fn facts(version: &str, comment: &str) -> ServerFacts {
        ServerFacts::from_probe(
            version.to_owned(),
            comment.to_owned(),
            false,
            "STRICT_TRANS_TABLES".to_owned(),
            false,
            None,
            42,
        )
    }

    fn present(rows: &[Row], feature: &str) -> bool {
        rows.iter()
            .find(|row| row["feature"] == json!(feature))
            .is_some_and(|row| row["present"] == json!(true))
    }

    /// Every optional feature appears whether it is there or not, so the
    /// caller learns the whole set from one answer.
    #[test]
    fn every_optional_feature_appears_present_or_absent() {
        let rows = features(&facts("10.11.8-MariaDB", "MariaDB Server"));
        assert_eq!(rows.len(), SINCE.len());
        assert!(rows.iter().all(|row| row.contains_key("present")));
    }

    /// A feature the destination is too old for is absent and says why.
    ///
    /// Anchored on a release older than the one this product supports, and
    /// deliberately so. Every feature on the list arrived by 10.4, and the
    /// oldest destination this product accepts is 10.11, so on a supported
    /// server nothing is ever absent and this path would go unmeasured. What is
    /// under test is the mechanism that reports an absence, not the support
    /// floor: it has to keep working for the day a newer feature joins the list.
    #[test]
    fn a_feature_the_release_is_too_old_for_says_why() {
        let rows = features(&facts("10.3.39-MariaDB", "MariaDB Server"));
        assert!(present(&rows, "system_versioning"));
        assert!(!present(&rows, "checked_documents"));
        let documents = rows
            .iter()
            .find(|row| row["feature"] == json!("checked_documents"))
            .expect("checked_documents is published");
        assert!(documents["absent_because"]
            .as_str()
            .is_some_and(|text| text.contains("10.4")));
    }

    /// On another server of the family nothing MariaDB-specific is claimed.
    #[test]
    fn another_server_claims_no_mariadb_feature() {
        let answer = run(&facts("8.0.36", "MySQL Community Server"));
        assert_eq!(answer.data["variant"], json!("other"));
        let rows = features(&facts("8.0.36", "MySQL Community Server"));
        assert!(rows.iter().all(|row| row["present"] == json!(false)));
    }

    /// A present feature carries no reason for an absence that did not happen.
    #[test]
    fn a_present_feature_carries_no_reason() {
        let rows = features(&facts("11.7.1-MariaDB", "MariaDB Server"));
        let documents = rows
            .iter()
            .find(|row| row["feature"] == json!("checked_documents"))
            .expect("checked_documents is published");
        assert_eq!(documents["absent_because"], Value::Null);
    }
}