mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Proving the mark of absence and the server-only families against a server.
//!
//! # Why this file exists
//!
//! Both requirements below were published as promises that nothing ran, and
//! both had a symbol in the tree that looked like the realiser and was not.
//! `with_comments` passed `TABLE_COMMENT` through and the answer carried the
//! empty string the catalogue keeps; `family_of` was complete and named no
//! family this server has and the wire cannot. A unit test could not have
//! caught either, because a projection spelled correctly against a catalogue
//! nobody asked reads as working, and a family that never meets a real value
//! is a name in a table.
//!
//! So every reading here drives the binary against the declared destination
//! and asserts on the answer that came back. What each proof builds it takes
//! away again, under a guard, so a failed assertion still leaves the server as
//! it was found.

// 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 serde_json::Value;
use support::server::{destination_or_skip, on_server, unique_mark};
use support::{Outcome, Sandbox};

/// The database every fixture of this file lives in.
const FIXTURE_DATABASE: &str = "shop";

/// The comment one fixture carries, to tell a written comment from no comment.
const WRITTEN_COMMENT: &str = "uma nota escrita de proposito";

/// The four listings the requirement about comments names.
const LISTINGS_WITH_A_COMMENT: &[&str] = &[
    "schema tables",
    "schema views",
    "schema indexes",
    "schema routines",
];

/// Objects this run alone built, taken away when the proof that made them ends.
struct Fixture<'a> {
    sandbox: &'a Sandbox,
    dsn: String,
    /// Every statement that has to be 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 statement that changes the shape of the server.
    fn statement(&self, written: &str) -> Outcome {
        on_server(self.sandbox, &self.dsn, &["--yes", "query", "run", written])
    }

    /// Writes rows so they survive the invocation that wrote them.
    ///
    /// The session this product opens holds its changes back until it is told
    /// to keep them, and a one-shot invocation that only ran the insertion
    /// closes without keeping anything. Measured: a row written through
    /// `query run` is gone by the next invocation. So rows are written the one
    /// way that keeps them, and a proof that read an empty table and called it
    /// a wrong answer is not possible here.
    fn fill(&self, written: &str) {
        let done = on_server(
            self.sandbox,
            &self.dsn,
            &["--yes", "query", "tx", "--statement", written],
        );
        assert_eq!(done.code, 0, "writing rows: {}", done.err);
    }

    /// 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.statement(statement);
        assert_eq!(built.code, 0, "the fixture must be built: {}", built.err);
        self.undo.push(undo);
    }

    /// Runs one reading inside the database the fixtures live in.
    fn read(&self, command: &[&str]) -> Outcome {
        let mut whole: Vec<&str> = command.to_vec();
        whole.extend_from_slice(&["--database", FIXTURE_DATABASE]);
        on_server(self.sandbox, &self.dsn, &whole)
    }
}

impl Drop for Fixture<'_> {
    fn drop(&mut self) {
        // Taken away in the reverse of the order they were built, so an object
        // that leans 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.statement(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 object 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}`"))
}

/// FR-122. An object with no comment answers with the mark of absence, and one
/// with a comment answers with the text somebody wrote.
///
/// The two halves are one proof on purpose. A build that answered the absence
/// marker for everything would satisfy the first half perfectly and be useless,
/// and one that answered the empty string for everything would have satisfied
/// the shape of the old check. Only both together say that the two conditions
/// are told apart.
#[test]
fn fr_122_a_table_without_a_comment_is_told_apart_from_one_with_an_empty_comment() {
    let Some(dsn) = destination_or_skip("the mark of absence on a comment") else {
        return;
    };
    let sandbox = Sandbox::new();
    let mut fixture = Fixture::new(&sandbox, &dsn);

    let silent = format!("comment_silent_{}", unique_mark());
    let speaking = format!("comment_speaking_{}", unique_mark());
    fixture.build(
        &format!("CREATE TABLE {silent} (n int)"),
        format!("DROP TABLE IF EXISTS {silent}"),
    );
    fixture.build(
        &format!("CREATE TABLE {speaking} (n int) COMMENT '{WRITTEN_COMMENT}'"),
        format!("DROP TABLE IF EXISTS {speaking}"),
    );

    let listed = fixture.read(&["schema", "tables", "--detail", "full"]);
    assert_eq!(listed.code, 0, "the listing must be served: {}", listed.err);
    let rows = listed.rows();

    let without = &row_named(&rows, &silent)["comment"];
    assert!(
        without.is_null(),
        "a table with no comment must carry the mark of absence, and carried {without}"
    );
    assert_ne!(
        without,
        &Value::from(""),
        "empty text is never the mark of absence"
    );

    assert_eq!(
        row_named(&rows, &speaking)["comment"],
        Value::from(WRITTEN_COMMENT),
        "a comment somebody wrote must arrive as the text they wrote"
    );
}

/// FR-122. The requirement names four listings, and all four mark the absence
/// of a comment rather than handing back the empty string.
///
/// The contract is read from the product first and the answer is compared
/// against it, so a listing that quietly stopped publishing the field, or one
/// that published it and never marked absence, fails here rather than being
/// discovered by whoever reads an empty string as a comment.
///
/// A view is the reason this is not folded into the proof above: this server
/// keeps no comment for one anywhere, and writes the kind of the object in the
/// place a comment would go. The requirement still names the listing, so the
/// field is published and always answers the mark of absence, which is the true
/// answer rather than the absence of an answer.
#[test]
fn fr_122_every_listing_the_requirement_names_marks_an_absent_comment() {
    let Some(dsn) = destination_or_skip("the mark of absence across the four listings") else {
        return;
    };
    let sandbox = Sandbox::new();
    let fixture = Fixture::new(&sandbox, &dsn);

    for command in LISTINGS_WITH_A_COMMENT {
        let contract = sandbox.run(&["meta", "schema", "--command", command]);
        assert_eq!(
            contract.code, 0,
            "the contract of `{command}`: {}",
            contract.err
        );
        let marked = contract.answer()["data"]["absent_when_missing"].clone();
        assert_eq!(
            marked,
            Value::from(vec!["comment"]),
            "`{command}` must publish that its comment carries the mark of absence"
        );

        let words: Vec<&str> = command.split(' ').collect();
        let mut asked: Vec<&str> = words.clone();
        asked.extend_from_slice(&["--detail", "full"]);
        let listed = fixture.read(&asked);
        assert_eq!(listed.code, 0, "`{command}` must be served: {}", listed.err);

        let rows = listed.rows();
        assert!(!rows.is_empty(), "`{command}` returned nothing to read");
        for row in &rows {
            let comment = &row["comment"];
            assert_ne!(
                comment,
                &Value::from(""),
                "`{command}` handed back empty text where the mark of absence belongs: {row}"
            );
            assert!(
                comment.is_null() || comment.is_string(),
                "`{command}` published a comment that is neither text nor the mark: {row}"
            );
        }
    }
}

/// The three families this server has that its result packet cannot name.
///
/// Written out here rather than read from the product, so the product agreeing
/// with itself proves nothing: the value written, the form the requirement
/// states, and the family the map must publish are all named in one place.
const SERVER_ONLY: &[(&str, &str, &str)] = &[
    ("uuid", "u", "123e4567-e89b-12d3-a456-426614174000"),
    ("inet4", "a", "192.0.2.7"),
    ("inet6", "b", "2001:0db8:0000:0000:0000:0000:0000:0001"),
];

/// FR-130. The published map names each family this server has and no other
/// does, and the form it states for each one is text.
#[test]
fn fr_130_the_published_map_names_every_server_only_family() {
    let sandbox = Sandbox::new();
    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();

    for (family, _, _) in SERVER_ONLY {
        let row = rows
            .iter()
            .find(|row| row["family"] == *family)
            .unwrap_or_else(|| panic!("the map publishes no family `{family}`"));
        assert_eq!(
            row["emitted"], "text",
            "`{family}` is rendered by the server already, so it leaves as text"
        );
        assert!(
            row["reason"].as_str().is_some_and(|note| !note.is_empty()),
            "`{family}` must say why it takes the form it takes"
        );
    }

    // The amendment also has to say two things no single row of the table
    // says: where the family of a value is read from, and that a document here
    // is text the server validates rather than a binary type of its own.
    let notes = answer["data"]["notes"]
        .as_array()
        .unwrap_or_else(|| panic!("the map carries no notes: {answer}"))
        .iter()
        .filter_map(|note| note.as_str())
        .collect::<Vec<_>>()
        .join(" ");
    for stated in ["catalogue declares", "validates", "guessing"] {
        assert!(
            notes.contains(stated),
            "the map never states `{stated}`: {notes}"
        );
    }
}

/// FR-130. A value of each server-only family, read back from the server, takes
/// exactly the form the published map states for it.
///
/// This is the half a unit test cannot reach. The wire packet of this server
/// does not tell these three apart from ordinary text, so a build could publish
/// all three families, convert none of them, and pass every reading that never
/// met a real column. Here one column of each is built, written, read, and the
/// text that came back is taken apart against the form the requirement states.
#[test]
fn fr_130_a_value_of_each_server_only_family_takes_the_published_form() {
    let Some(dsn) = destination_or_skip("a value of each server-only family") else {
        return;
    };
    let sandbox = Sandbox::new();
    let mut fixture = Fixture::new(&sandbox, &dsn);

    let table = format!("server_only_{}", unique_mark());
    fixture.build(
        &format!("CREATE TABLE {table} (u uuid, a inet4, b inet6)"),
        format!("DROP TABLE IF EXISTS {table}"),
    );
    let written: Vec<&str> = SERVER_ONLY.iter().map(|(_, _, value)| *value).collect();
    fixture.fill(&format!(
        "INSERT INTO {table} VALUES ('{}', '{}', '{}')",
        written[0], written[1], written[2]
    ));

    // The catalogue is what names these families, so it is asserted too: the
    // whole conversion rests on the declared type, and a server that named them
    // differently would make the rule unreachable without saying so.
    let described = fixture.read(&["schema", "columns", "--table", &table]);
    assert_eq!(described.code, 0, "the description: {}", described.err);
    let described_rows = described.rows();
    for (family, column, _) in SERVER_ONLY {
        assert_eq!(
            row_named(&described_rows, column)["type"],
            Value::from(*family),
            "the catalogue must declare `{column}` as `{family}`"
        );
    }

    let read = on_server(
        &sandbox,
        &dsn,
        &[
            "query",
            "run",
            &format!("SELECT u, a, b FROM {FIXTURE_DATABASE}.{table}"),
        ],
    );
    assert_eq!(read.code, 0, "reading the row back: {}", read.err);
    let rows = read.rows();
    assert_eq!(rows.len(), 1, "one row was written: {}", read.out);
    let row = &rows[0];

    for (family, column, _) in SERVER_ONLY {
        assert!(
            row[*column].is_string(),
            "`{family}` is published as text and arrived as {}",
            row[*column]
        );
    }

    let identifier = row["u"].as_str().expect("text");
    assert!(
        is_canonical_identifier(identifier),
        "the identifier must be canonical text with its hyphens, and was `{identifier}`"
    );

    let fourth = row["a"].as_str().expect("text");
    assert_eq!(
        fourth.parse::<std::net::Ipv4Addr>().ok(),
        written[1].parse().ok(),
        "the fourth-version address must be four numbers separated by dots"
    );
    assert_eq!(
        fourth.split('.').count(),
        4,
        "`{fourth}` is not four numbers"
    );

    let sixth = row["b"].as_str().expect("text");
    assert_eq!(
        sixth.parse::<std::net::Ipv6Addr>().ok(),
        written[2].parse().ok(),
        "the sixth-version address must be the address that was written"
    );
    // Written out in full and read back shortened: that is the server's own
    // canonical form arriving untouched. A build that re-rendered the address
    // itself would be free to hand back the expanded text, and this is what
    // says it did not.
    assert_ne!(
        sixth, written[2],
        "the sixth-version address must arrive in the server's shortened form"
    );
    assert!(
        sixth.contains("::"),
        "the shortened form collapses its run of zeroes, and `{sixth}` did not"
    );
}

/// Whether text is an identifier in the canonical form, hyphens included.
fn is_canonical_identifier(text: &str) -> bool {
    let separators = [8, 13, 18, 23];
    text.len() == 36
        && text.char_indices().all(|(at, letter)| {
            if separators.contains(&at) {
                letter == '-'
            } else {
                letter.is_ascii_hexdigit()
            }
        })
}