mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Proving the two readings that only a working server can settle.
//!
//! # Why this file exists
//!
//! Two published requirements were carried by proofs of SHAPE. The ranking of
//! costly statements was shown to have the fields it promises, against whatever
//! the destination happened to be holding, so nothing said the ranking reports
//! work this product itself caused. The structural warning was shown over rows
//! written by hand, so nothing said the catalogue of a real server ever
//! produces the shapes the rule is written for.
//!
//! Each proof here therefore makes the server hold something first — work in
//! one case, structure in the other — and then asks the published command about
//! exactly that. Every object is made by the run that reads it, named from a
//! mark no other run repeats, and taken away when the run ends.

// The support module serves every test file in this directory, so the parts
// this one does not need are unused here and used elsewhere.
#[allow(dead_code)]
mod support;

use serde_json::Value;
use support::server::{aimed_at, destination_or_skip, Scratch};

/// The database these proofs are allowed to create tables in.
///
/// Never the one the destination names by itself: that one is shared with every
/// other proof of this suite, and a file that creates and drops tables belongs
/// somewhere set aside for exactly that.
const WRITABLE: &str = "bulk";

/// A value no other statement of this suite writes.
///
/// Held in the table the ranking is made to read, so the answer can be searched
/// for it: a signature that carried it would be leaking what the application
/// stores, which is the one thing the requirement forbids.
const OWN_VALUE: &str = "918273645";

/// How far down the ranking the reading goes.
///
/// Well past the number of signatures such a server keeps, because the ranking
/// is ordered by total time and the trifling work these proofs cause sits at
/// the very bottom of it.
const DEEP_ENOUGH: &str = "5000";

/// A destination aimed at the writable database, or nothing when none was
/// declared.
fn writable(proof: &str) -> Option<String> {
    destination_or_skip(proof).map(|dsn| aimed_at(&dsn, WRITABLE))
}

/// FR-127. The ranking of costliest statements reports work this product made
/// the server do: a copy taken twice from a table of this run's own appears as
/// ONE signature counted twice, and that signature carries the table's name and
/// never the value the rows held.
///
/// Reading the ranking of a busy server proves nothing about the product, since
/// the rows would be there either way. Causing the work first is what makes the
/// answer an answer about this invocation, and taking the copy twice is what
/// shows two runs of one statement grouping rather than accumulating.
#[test]
fn the_ranking_reports_work_this_product_made_the_server_do() {
    let Some(dsn) = writable("the_ranking_reports_work_this_product_made_the_server_do") else {
        return;
    };
    let table = Scratch::new(&dsn, WRITABLE, "a BIGINT");
    table.seed(&format!("({OWN_VALUE})"));

    let copy = table.sandbox.path().join("copy.sql");
    let copy = copy.to_string_lossy().into_owned();
    for _ in 0..2 {
        let taken = table.run(&["data", "export", "--table", table.name(), "--to", &copy]);
        assert_eq!(
            taken.code, 0,
            "the server must be made to work: {}",
            taken.err
        );
    }

    let ranked = table.run(&["server", "queries", "--top", DEEP_ENOUGH]);
    assert_eq!(ranked.code, 0, "the ranking must be served: {}", ranked.err);

    let signature = |row: &Value| row["signature"].as_str().unwrap_or_default().to_owned();
    let mine: Vec<Value> = ranked
        .rows()
        .into_iter()
        .filter(|row| {
            let said = signature(row);
            said.contains(table.name()) && said.contains("SELECT")
        })
        .collect();
    assert_eq!(
        mine.len(),
        1,
        "one statement run twice must rank as one signature: {mine:?}"
    );
    assert_eq!(
        mine[0]["calls"], 2,
        "the ranking did not count both runs of the one statement: {:?}",
        mine[0]
    );
    assert!(
        !signature(&mine[0]).contains(OWN_VALUE),
        "the signature carries what the rows held: {}",
        signature(&mine[0])
    );
}

/// FR-140. A link the server really holds, left with no index leading with its
/// columns, is named by the published listing when the warning is asked for —
/// and the same listing without the mark carries no finding at all.
///
/// The link is made unsupported the only way a server allows: the index the
/// engine creates for itself is removed inside a session that was told not to
/// check links, which is a setting of that one session and never of the server.
/// The second half is asserted because a listing that always warned would pass
/// the first half while telling the caller nothing.
#[test]
fn a_link_the_server_holds_without_a_supporting_index_is_named() {
    let Some(dsn) = writable("a_link_the_server_holds_without_a_supporting_index_is_named") else {
        return;
    };
    // Declared first so it is dropped last: the table pointing at it has to go
    // before the table it points at.
    let pointed_at = Scratch::new(&dsn, WRITABLE, "id INT NOT NULL PRIMARY KEY");
    let pointing = Scratch::new(
        &dsn,
        WRITABLE,
        &format!(
            "a INT, FOREIGN KEY (a) REFERENCES {} (id)",
            pointed_at.qualified()
        ),
    );

    let listed = pointing.run(&["schema", "indexes", "--table", pointing.name()]);
    assert_eq!(listed.code, 0, "the indexes must be listed: {}", listed.err);
    let support = listed
        .rows()
        .into_iter()
        .find(|row| row["column"] == "a")
        .map(|row| row["name"].as_str().unwrap_or_default().to_owned())
        .expect("the engine makes an index for a link of its own accord");

    let relaxed = pointing.sandbox.run(&[
        "config",
        "set",
        "conn.session_setup",
        "SET foreign_key_checks=0",
    ]);
    assert_eq!(
        relaxed.code, 0,
        "the session setting must be storable: {}",
        relaxed.err
    );
    let removed = pointing.run(&[
        "--yes",
        "query",
        "run",
        &format!(
            "ALTER TABLE {} DROP INDEX `{support}`",
            pointing.qualified()
        ),
    ]);
    assert_eq!(
        removed.code, 0,
        "the supporting index must be removable: {}",
        removed.err
    );

    let quiet = pointing.run(&["schema", "keys", "--table", pointing.name()]);
    assert_eq!(quiet.code, 0, "the keys must be listed: {}", quiet.err);
    assert!(
        quiet.answer()["data"]["advice"].is_null(),
        "a listing nobody asked to warn carried a finding: {}",
        quiet.out
    );

    let warned = pointing.run(&["schema", "keys", "--table", pointing.name(), "--warn"]);
    assert_eq!(warned.code, 0, "the warning must be served: {}", warned.err);
    let found = warned.answer()["data"]["advice"]["links_without_support"]
        .as_array()
        .unwrap_or_else(|| panic!("the warning carries no finding: {}", warned.out))
        .clone();
    assert_eq!(
        found.len(),
        1,
        "the unsupported link was not named: {found:?}"
    );
    assert_eq!(found[0]["table"], pointing.name());
    assert_eq!(found[0]["columns"], serde_json::json!(["a"]));
    assert_eq!(
        found[0]["references"],
        format!("{WRITABLE}.{}", pointed_at.name()),
        "the finding must say what the link points at"
    );
}

/// FR-140. An index the server really holds, whose columns are the first
/// columns of another index of the same table, is named together with the index
/// that already covers it — and the wider one is never the one named.
///
/// Both indexes are declared on one table so the server itself decides what the
/// catalogue reports; the rule was only ever shown over rows written by hand,
/// which cannot say whether a real catalogue produces that shape.
#[test]
fn an_index_the_server_holds_inside_another_is_named_with_its_cover() {
    let Some(dsn) = writable("an_index_the_server_holds_inside_another_is_named_with_its_cover")
    else {
        return;
    };
    let table = Scratch::new(
        &dsn,
        WRITABLE,
        "b INT, c INT, KEY narrow (b), KEY wide (b, c)",
    );

    let quiet = table.run(&["schema", "indexes", "--table", table.name()]);
    assert_eq!(quiet.code, 0, "the indexes must be listed: {}", quiet.err);
    assert!(
        quiet.answer()["data"]["advice"].is_null(),
        "a listing nobody asked to warn carried a finding: {}",
        quiet.out
    );

    let warned = table.run(&["schema", "indexes", "--table", table.name(), "--warn"]);
    assert_eq!(warned.code, 0, "the warning must be served: {}", warned.err);
    let found = warned.answer()["data"]["advice"]["covered_indexes"]
        .as_array()
        .unwrap_or_else(|| panic!("the warning carries no finding: {}", warned.out))
        .clone();
    assert_eq!(
        found.len(),
        1,
        "exactly one of the pair is named: {found:?}"
    );
    assert_eq!(
        found[0]["index"], "narrow",
        "the wider index was named instead of the one it covers"
    );
    assert_eq!(found[0]["covered_by"], "wide");
    assert_eq!(
        found[0]["covering_columns"],
        serde_json::json!(["b", "c"]),
        "the finding must say which columns already cover it"
    );
}