mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! What the primary channel carries, and how much of a context it costs.
//!
//! # Why these proofs sit together
//!
//! Both are about the bytes a caller receives and nothing else. One half asks
//! whether those bytes are the same twice, free of the host's conventions, and
//! shaped by a type map nobody can reconfigure. The other half asks how many of
//! them there are, because an answer that is correct and does not fit is an
//! answer an agent cannot use.
//!
//! Nothing here needs a destination: the shape of an answer and the size of a
//! map are both decided before a statement is ever sent.

// Each file here uses the part of the shared module that it needs, so a helper
// unused by this one is not dead code.
#[allow(dead_code)]
mod support;

use mariadb_cli::output::envelope::Row;
use mariadb_cli::types::{Family, Shape};
use serde_json::{json, Value};
use support::Sandbox;

// ---------------------------------------------------------------------------
// Proof 2 — the primary channel is clean and predictable
// ---------------------------------------------------------------------------

/// The same query twice, with every diagnostic on, gives the same bytes.
///
/// The diagnostics are what would leak into the answer if the two channels were
/// ever crossed, so turning them up is the interesting case rather than the
/// awkward one.
///
/// FR-064. Two runs of one call are compared byte for byte and must not differ.
///
/// FR-050. Raising the detail of the diagnostics changes nothing on the primary
/// channel, which is asserted by the same comparison being made with `-vvv` on.
#[test]
fn the_same_call_twice_under_full_diagnostics_gives_identical_bytes() {
    let sandbox = Sandbox::new();
    let first = sandbox.run(&["-vvv", "meta", "schema", "--types"]);
    let second = sandbox.run(&["-vvv", "meta", "schema", "--types"]);

    assert_eq!(first.code, 0, "{}", first.err);
    assert_eq!(
        first.out, second.out,
        "two runs of the same call must carry the same bytes"
    );
    assert!(
        !first.err.is_empty() || first.out.contains("family"),
        "the diagnostics were asked for and the answer still stands alone"
    );
}

/// The answer parses with no editing, whatever the auxiliary channel said.
///
/// FR-050. The primary channel stays parseable while the diagnostics are at
/// their loudest, which is the whole content of keeping the two apart.
#[test]
fn the_answer_parses_without_editing_under_full_diagnostics() {
    let sandbox = Sandbox::new();
    let outcome = sandbox.run(&["-vvv", "meta", "commands"]);
    let answer = outcome.answer();
    assert_eq!(answer["command"], "meta commands");
    assert!(answer["data"]["rows"].is_array());
}

/// The bytes follow the product's own rule and never the host's convention.
///
/// One line ending, no carriage return and no byte order mark, so the same call
/// on another system produces the same bytes.
///
/// FR-096. The three things the requirement names — no carriage return, no byte
/// order mark, one line ending — are each asserted on real output.
#[test]
fn the_primary_channel_carries_no_carriage_return_and_no_byte_order_mark() {
    let sandbox = Sandbox::new();
    let written = sandbox.run(&["meta", "schema", "--types"]).out;

    assert!(
        !written.contains('\r'),
        "a carriage return reached the answer"
    );
    assert!(
        !written.starts_with('\u{feff}'),
        "a byte order mark reached the answer"
    );
    assert!(
        written.ends_with('\n'),
        "the answer ends with one line ending"
    );
}

/// Every family the type map publishes emits the form the specification names.
///
/// The table below is written out from the requirement rather than read from
/// the product, so the product agreeing with itself proves nothing here.
///
/// FR-094. Each of the twenty-two families the annex tabulates is looked up in
/// the published map and its emitted form compared against the one written here.
///
/// FR-130. The last three are the amendment: the families this server has and no
/// other does. Each leaves as text because the server renders it before it
/// leaves — the identifier in its canonical form with hyphens, the
/// fourth-version address as four numbers separated by dots, the sixth-version
/// address in the server's own shortened canonical form.
///
/// FR-043. The same comparison is what makes the conversion predictable: a wide
/// integer and an exact decimal must leave as text rather than as a number that
/// quietly lost digits.
#[test]
fn every_published_family_emits_the_form_the_requirement_names() {
    let published: Vec<(&str, &str)> = vec![
        ("integer", "number"),
        ("wide_integer", "text"),
        ("exact_decimal", "text"),
        ("floating_point", "number"),
        ("text", "text"),
        ("absent", "absent"),
        ("bits", "number"),
        ("date", "text"),
        ("date_time", "text"),
        ("timestamp", "text"),
        ("time", "text"),
        ("year", "number"),
        ("single_choice", "text"),
        ("choice_set", "text"),
        ("document", "structure"),
        ("binary", "description"),
        ("geometry", "text"),
        ("unknown", "text"),
        ("uuid", "text"),
        ("inet4", "text"),
        ("inet6", "text"),
    ];

    let sandbox = Sandbox::new();
    let rows = sandbox.run(&["meta", "schema", "--types"]).rows();
    assert_eq!(
        rows.len(),
        published.len(),
        "the published table and the requirement must name the same families"
    );

    for (family, emitted) in published {
        let row = rows
            .iter()
            .find(|row| row["family"] == family)
            .unwrap_or_else(|| panic!("the map publishes no family `{family}`"));
        assert_eq!(
            row["emitted"], emitted,
            "`{family}` must be emitted as {emitted}"
        );
    }
}

/// The type map is a fixed table, so a family and its form never drift apart.
///
/// FR-094. The requirement states the table is fixed and not configurable, and
/// the second half of this test is what "not configurable" has to mean in
/// practice: no key of the registry governs the map.
#[test]
fn the_type_map_is_fixed_and_cannot_be_configured() {
    for entry in mariadb_cli::types::published() {
        assert_eq!(
            entry.shape,
            entry.family.shape(),
            "{}",
            entry.family.as_str()
        );
    }
    // No key of the registry governs the map, which is what "not configurable"
    // has to mean in practice.
    let governing: Vec<&str> = mariadb_cli::config::keys::all()
        .iter()
        .map(|entry| entry.name)
        .filter(|name| name.starts_with("types."))
        .collect();
    assert!(
        governing.is_empty(),
        "the map is configurable through {governing:?}"
    );

    assert_eq!(Family::Document.shape(), Shape::Structure);
    assert_eq!(Family::ExactDecimal.shape(), Shape::Text);
}

// ---------------------------------------------------------------------------
// Proof 3 — the agent's context fits
// ---------------------------------------------------------------------------

/// The compact map is at least ten times smaller than the full description.
///
/// Both sides are built from the same readings, so what is compared is the
/// shape of the two answers and never two different databases.
///
/// FR-020. The requirement's own way of showing it holds is the ratio, and the
/// ratio is what the last assertion measures.
#[test]
fn the_compact_map_is_at_least_ten_times_smaller_than_the_full_description() {
    let (tables, columns, links) = a_database_of_many_tables(300);

    let (map, gaps) = mariadb_cli::introspect::map::compose(
        &tables,
        &columns,
        &links,
        false,
        mariadb_cli::introspect::map::Budget {
            tables: 1000,
            rows: 100_000,
        },
    );
    assert!(gaps.is_empty(), "nothing was left out: {gaps:?}");

    let compact = serde_json::to_string(&map).expect("serialises").len();
    let full = serde_json::to_string(&json!({"rows": columns}))
        .expect("serialises")
        .len();

    assert!(
        full >= compact * 10,
        "the map is {compact} bytes and the full description {full}; \
         the map must be at least ten times smaller"
    );
}

/// A byte column and a vector column add their names to the map and nothing else.
///
/// FR-020. A large column must not swell the skeleton, which the first assertion
/// measures by looking for its declared type in the written map.
///
/// FR-066. A binary value leaves as a description carrying its size, and the
/// content is asserted absent rather than merely small.
///
/// The second column is here because `vector(1536)` is the widest declaration
/// the catalogue hands back, and width is what this proof is about. The map has
/// to drop it like any other, so the widest case is the one worth asserting on.
#[test]
fn no_binary_or_vector_column_swells_the_map_with_content() {
    let (tables, mut columns, links) = a_database_of_many_tables(1);
    columns.push(catalog_column("t0", "picture", "longblob", false));
    columns.push(catalog_column("t0", "embedding", "vector(1536)", false));

    let budget = mariadb_cli::introspect::map::Budget {
        tables: 10,
        rows: 100,
    };
    let (map, _) = mariadb_cli::introspect::map::compose(&tables, &columns, &links, false, budget);
    let written = serde_json::to_string(&map).expect("serialises");

    assert!(
        !written.contains("longblob") && !written.contains("vector(1536)"),
        "the map carries the full type of a large column: {written}"
    );

    // And the value side never emits content either, whatever the column holds.
    let described = mariadb_cli::types::binary::describe(
        &[0xFFu8; 4096],
        &mariadb_cli::types::Conversion::stable().binary,
    )
    .expect("a description is always available");
    assert_eq!(described["bytes"], 4096);
    assert!(
        described.get("content").is_none(),
        "the content left without being asked for: {described}"
    );
}

/// The readings a database of `count` tables would produce.
fn a_database_of_many_tables(count: usize) -> (Vec<Row>, Vec<Row>, Vec<Row>) {
    let mut tables = Vec::new();
    let mut columns = Vec::new();
    for index in 0..count {
        let name = format!("t{index}");
        let mut table = Row::new();
        table.insert("name".to_owned(), json!(name));
        table.insert("database".to_owned(), json!("loja"));
        tables.push(table);

        columns.push(catalog_column(&name, "id", "bigint(20) unsigned", true));
        columns.push(catalog_column(&name, "descricao", "varchar(255)", false));
        columns.push(catalog_column(&name, "criado_em", "datetime(6)", false));
    }
    (tables, columns, Vec::new())
}

/// One column exactly as the catalogue reading describes it.
fn catalog_column(table: &str, name: &str, declared: &str, key: bool) -> Row {
    let mut row = Row::new();
    row.insert("table".to_owned(), json!(table));
    row.insert("database".to_owned(), json!("loja"));
    row.insert("name".to_owned(), json!(name));
    row.insert("type".to_owned(), json!(declared));
    row.insert(
        "base_type".to_owned(),
        json!(declared.split('(').next().unwrap_or(declared)),
    );
    row.insert("nullable".to_owned(), json!(!key));
    row.insert("default".to_owned(), Value::Null);
    row.insert("comment".to_owned(), json!(""));
    row.insert("key".to_owned(), json!(if key { "PRI" } else { "" }));
    row
}