mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Proving type printing and column origin against a real server.
//!
//! # Why this file exists
//!
//! These two requirements are the same family as the defect this round came
//! from. There the published map of type printing agreed with an artefact this
//! suite built and disagreed with the server, and nobody saw it because the
//! proof was built from the same artefact. Type printing was still being read
//! over columns this suite assembled, and column origin was still being read
//! over column packets this suite assembled, so both were open the same way.
//!
//! So every reading here builds real columns on the declared destination,
//! writes real values into them, asks the SERVER what it declared them to be,
//! and compares the product's printing against the form the published map
//! states for the family the server named. The three families this server has
//! that no result packet can name — the identifier and the two address kinds —
//! are covered here for the same reason: nothing but a real column proves them.
//!
//! Whatever a proof builds it takes away again in a guard, so a failed
//! assertion still leaves the server as it was found.

// The support module serves every proof file in this directory, so the parts
// this one does not need are used by its neighbours.
#[allow(dead_code)]
mod support;

use serde_json::Value;
use support::server::{aimed_at, destination_or_skip, on_server, unique_mark};
use support::{Outcome, Sandbox};

/// The database these proofs are allowed to build in.
const WRITABLE: &str = "bulk";

/// The shape of the table every type reading below is taken from.
const TYPED_SHAPE: &str = "\
    n INT, w BIGINT, d DECIMAL(30,10), f DOUBLE, s VARCHAR(30), em VARCHAR(30), \
    b BLOB, dt DATETIME(6), ts TIMESTAMP NULL, da DATE, tm TIME, y YEAR, \
    bi BIT(8), e ENUM('a','b'), st SET('x','y'), u uuid, a4 inet4, a6 inet6, \
    missing INT";

/// The one row every type reading below is taken from.
const TYPED_ROW: &str = "(\
    42, 9223372036854775807, 12345678901234567890.1234567890, 1.5, 'txt', '', \
    'bytes', '2024-03-01 10:20:30.123456', '2024-03-01 10:20:30', '2024-03-01', \
    '10:20:30', 2024, b'10101010', 'a', 'x,y', \
    '123e4567-e89b-12d3-a456-426614174000', '192.0.2.7', \
    '2001:0db8:0000:0000:0000:0000:0000:0001', NULL)";

/// The exact digits written into the decimal column, which must survive whole.
const WRITTEN_DECIMAL: &str = "12345678901234567890.1234567890";

/// Every column of the fixture, with the type the SERVER must declare for it
/// and the family the published map must name.
///
/// Written out here rather than read from the product, so the product agreeing
/// with itself proves nothing: what the catalogue says, what family it belongs
/// to and what form the map states for that family are three separate readings
/// that this table forces to meet.
const COVERED: &[(&str, &str, &str)] = &[
    ("n", "int(11)", "integer"),
    ("w", "bigint(20)", "wide_integer"),
    ("d", "decimal(30,10)", "exact_decimal"),
    ("f", "double", "floating_point"),
    ("s", "varchar(30)", "text"),
    ("em", "varchar(30)", "text"),
    ("b", "blob", "binary"),
    ("dt", "datetime(6)", "date_time"),
    ("ts", "timestamp", "timestamp"),
    ("da", "date", "date"),
    ("tm", "time", "time"),
    ("y", "year(4)", "year"),
    ("bi", "bit(8)", "bits"),
    ("e", "enum('a','b')", "single_choice"),
    ("st", "set('x','y')", "choice_set"),
    ("u", "uuid", "uuid"),
    ("a4", "inet4", "inet4"),
    ("a6", "inet6", "inet6"),
    ("missing", "int(11)", "absent"),
];

/// A destination this file may build in, or nothing when none was declared.
fn writable(proof: &str) -> Option<String> {
    destination_or_skip(proof).map(|dsn| aimed_at(&dsn, WRITABLE))
}

/// Objects this run alone built, taken away when the proof that made them ends.
struct Fixture<'a> {
    /// Where the invocations are driven from.
    sandbox: &'a Sandbox,
    /// The destination the objects live on.
    dsn: String,
    /// Every statement that has to run to leave the server as it was found.
    undo: Vec<String>,
}

impl<'a> Fixture<'a> {
    /// An empty holding, which owns nothing until something is built into it.
    fn new(sandbox: &'a Sandbox, dsn: &str) -> Self {
        Self {
            sandbox,
            dsn: dsn.to_owned(),
            undo: Vec::new(),
        }
    }

    /// Runs one invocation against the destination these objects live on.
    fn run(&self, args: &[&str]) -> Outcome {
        on_server(self.sandbox, &self.dsn, args)
    }

    /// Builds one object and records how to take it away.
    ///
    /// # Panics
    ///
    /// Panics when the server refuses to build it, which is the proof's own
    /// ground giving way rather than a reason to carry on without a subject.
    fn build(&mut self, statement: &str, undo: String) {
        let built = self.run(&["--yes", "query", "run", statement]);
        assert_eq!(built.code, 0, "the fixture must be built: {}", built.err);
        self.undo.push(undo);
    }

    /// Writes rows so they outlive the invocation that wrote them.
    ///
    /// # Panics
    ///
    /// Panics when the rows cannot be written.
    fn fill(&self, statement: &str) {
        let written = self.run(&["--yes", "query", "tx", "--statement", statement]);
        assert_eq!(written.code, 0, "the rows must be written: {}", written.err);
    }
}

impl Drop for Fixture<'_> {
    fn drop(&mut self) {
        // Taken away in the reverse of the order they were built, so an object
        // leaning on an earlier one goes first. What a failed removal means is
        // decided in one place for every fixture of this suite, because each
        // deciding for itself produced eight silences and two aborts.
        for undo in self.undo.iter().rev() {
            let removed = self.run(&["--yes", "query", "run", undo]);
            support::server::confirm_removed(&removed, undo);
        }
    }
}

/// The row of a listing whose name is the one asked for.
///
/// # Panics
///
/// Panics when the listing carries no such row, which means the reading under
/// test never reached the column the proof built.
fn row_named<'a>(rows: &'a [Value], name: &str) -> &'a Value {
    rows.iter()
        .find(|row| row["name"] == name)
        .unwrap_or_else(|| panic!("the listing carries no `{name}`"))
}

/// The form the published map states for one family.
///
/// # Panics
///
/// Panics when the map names no such family, which is itself the failure: a
/// column the server has and the map does not name cannot be printed to a rule.
fn published_form(sandbox: &Sandbox, family: &str) -> String {
    let answer = sandbox.run(&["meta", "schema", "--types"]).answer();
    let rows = answer["data"]["rows"]
        .as_array()
        .unwrap_or_else(|| panic!("the map carries no rows: {answer}"))
        .clone();
    rows.iter()
        .find(|row| row["family"] == family)
        .unwrap_or_else(|| panic!("the map publishes no family `{family}`"))["emitted"]
        .as_str()
        .unwrap_or_default()
        .to_owned()
}

/// Whether one value really takes the form the published map states.
fn takes_the_form(value: &Value, form: &str) -> bool {
    match form {
        "number" => value.is_number(),
        "text" => value.is_string(),
        "absent" => value.is_null(),
        "structure" => value.is_object() || value.is_array(),
        // A described value is an object standing in for content that never
        // travels, so what says it is described is the kind it declares.
        "description" => value.is_object() && value["kind"].is_string(),
        _ => false,
    }
}

/// FR-043. A column of every family this server can declare is built, written,
/// and read back, and the form each value takes is exactly the form the
/// published map states for the family the SERVER declared that column to be.
///
/// This is the reading a local one cannot reach. The three families that no
/// result packet can name are told apart by the declared type alone, so a build
/// could publish them, convert none of them, and pass every reading that never
/// met a real column. The decimal is asserted digit for digit for the same
/// reason: silent rounding is exactly what a printing rule assembled locally
/// would never show.
#[test]
fn fr_043_every_family_the_server_declares_is_printed_in_the_published_form() {
    let Some(dsn) = writable("the printed form of every declared family") else {
        return;
    };
    let sandbox = Sandbox::new();
    let mut fixture = Fixture::new(&sandbox, &dsn);

    let table = format!("typed_{}", unique_mark());
    fixture.build(
        &format!("CREATE TABLE {table} ({TYPED_SHAPE})"),
        format!("DROP TABLE IF EXISTS {table}"),
    );
    fixture.fill(&format!("INSERT INTO {table} VALUES {TYPED_ROW}"));

    let described = fixture.run(&["schema", "columns", "--table", &table]);
    assert_eq!(
        described.code, 0,
        "the description must be served: {}",
        described.err
    );
    let described_rows = described.rows();

    let read = fixture.run(&["query", "run", &format!("SELECT * FROM {WRITABLE}.{table}")]);
    assert_eq!(read.code, 0, "the read must be served: {}", read.err);
    let rows = read.rows();
    assert_eq!(rows.len(), 1, "one row was written: {}", read.out);
    let row = &rows[0];

    for (column, declared, family) in COVERED {
        assert_eq!(
            row_named(&described_rows, column)["type"],
            Value::from(*declared),
            "the server must declare `{column}` as `{declared}`, which is what \
             makes its family `{family}` something the server said"
        );
        let form = published_form(&sandbox, family);
        assert!(
            takes_the_form(&row[*column], &form),
            "`{column}` is of family `{family}`, published as `{form}`, and the \
             server's own value arrived as {}",
            row[*column]
        );
    }

    // The requirement states these three outright, so they are asserted as
    // themselves rather than only through the form above.
    assert_eq!(
        row["d"],
        Value::from(WRITTEN_DECIMAL),
        "a large decimal must arrive with every digit it was written with"
    );
    assert_eq!(
        row["em"],
        Value::from(""),
        "empty text is text the server holds and must arrive as text"
    );
    assert!(
        row["missing"].is_null(),
        "absence must be its own mark and never empty text: {}",
        row["missing"]
    );
    assert_ne!(row["em"], row["missing"], "absence was told for empty text");
}

/// FR-073. The origin the product reports for each result column names tables
/// and columns the SERVER really holds, and an unqualified column across a
/// junction is refused rather than guessed at.
///
/// The claim of this requirement is about physical origin, so the check is that
/// every table and column it named is one the destination's catalogue lists.
/// A reading over packets this file assembled could only ever say the answer
/// was well formed; only asking the server says it was true.
#[test]
fn fr_073_the_reported_origin_names_columns_the_server_really_holds() {
    let Some(dsn) = writable("the physical origin of the result columns") else {
        return;
    };
    let sandbox = Sandbox::new();
    let mut fixture = Fixture::new(&sandbox, &dsn);

    let parent = format!("origin_parent_{}", unique_mark());
    let child = format!("origin_child_{}", unique_mark());
    fixture.build(
        &format!("CREATE TABLE {parent} (id INT PRIMARY KEY, label VARCHAR(20))"),
        format!("DROP TABLE IF EXISTS {parent}"),
    );
    fixture.build(
        &format!(
            "CREATE TABLE {child} (id INT PRIMARY KEY, pid INT, amount INT, \
             FOREIGN KEY (pid) REFERENCES {parent}(id))"
        ),
        format!("DROP TABLE IF EXISTS {child}"),
    );

    let traced = fixture.run(&[
        "query",
        "lineage",
        &format!(
            "SELECT c.amount, p.label, c.amount + 1 AS bumped \
             FROM {child} c JOIN {parent} p ON p.id = c.pid"
        ),
    ]);
    assert_eq!(traced.code, 0, "the origin must be served: {}", traced.err);
    let rows = traced.rows();
    assert_eq!(
        rows.len(),
        3,
        "three result columns were asked for: {}",
        traced.out
    );

    let mut seen = 0usize;
    for row in &rows {
        let sources = row["sources"]
            .as_array()
            .unwrap_or_else(|| panic!("a result column resolved to nothing: {row}"))
            .clone();
        assert!(
            !sources.is_empty(),
            "every result column must resolve to a physical one: {row}"
        );
        for source in &sources {
            let table = source["table"].as_str().unwrap_or_default();
            let column = source["column"].as_str().unwrap_or_default();
            assert!(
                table == parent || table == child,
                "`{table}` is not one of the tables this statement reads"
            );

            // The server is asked whether it really holds that column, which is
            // the whole difference between a well formed answer and a true one.
            let held = fixture.run(&["schema", "columns", "--table", table]);
            assert_eq!(held.code, 0, "the description of `{table}`: {}", held.err);
            assert!(
                held.rows().iter().any(|one| one["name"] == column),
                "the origin names `{table}.{column}` and the server holds no such column"
            );
            seen += 1;
        }
    }
    assert!(
        seen >= 3,
        "only {seen} origins were checked against the server"
    );

    // An unqualified name that both tables carry: the answer is refused whole
    // rather than resolved to whichever of the two came first.
    let refused = fixture.run(&[
        "query",
        "lineage",
        &format!("SELECT id FROM {child} JOIN {parent} ON {parent}.id = {child}.pid"),
    ]);
    assert_eq!(
        refused.code, 3,
        "an ambiguous column must be refused: {}",
        refused.err
    );
    assert_eq!(refused.code(), "lineage.ambiguous_column");
    assert!(
        refused.failure()["error"]["message"]
            .as_str()
            .is_some_and(|said| said.contains("id")),
        "the refusal must name the column it is about"
    );
}