mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Calling code that lives inside the server.
//!
//! # Why these proofs sit together
//!
//! A routine is the one thing this product sends without being able to read
//! it. Every other statement can be looked at and classified before it goes;
//! the body of a routine cannot, so the product has to treat the call as
//! capable of anything. That single decision is what all three proofs below
//! turn on: it is why the call needs confirmation even when it only counts
//! rows, why whatever comes back has to be kept apart set by set rather than
//! folded into one, and why a value that never appears as a row still has to
//! reach the caller.
//!
//! The routine used here belongs to the declared destination rather than to
//! this file. It cannot be created from here: the statement that would create
//! one carries its own body, and a body is several statements, which this
//! product refuses to send as one text — correctly, and for reasons proved
//! elsewhere.

// This file uses the part of the shared module that it needs, so a helper used
// only by its neighbours is not dead code here.
#[allow(dead_code)]
mod support;

use support::server::{destination_or_skip, on_server};
use support::Sandbox;

/// The routine the declared destination carries.
///
/// It takes a floor and answers, through an output parameter and never through
/// a row, how many orders reach that floor.
const ROUTINE: &str = "count_orders";

/// How many orders reach a given floor, asked directly rather than through the
/// routine.
///
/// This is the second opinion the proof of the output parameter needs: a value
/// that came back from the call is only worth something next to the number the
/// same question answers when it is asked in the ordinary way.
fn orders_reaching(sandbox: &Sandbox, dsn: &str, floor: &str) -> i64 {
    let counted = on_server(
        sandbox,
        dsn,
        &[
            "query",
            "run",
            &format!("SELECT COUNT(*) AS reaching FROM orders WHERE total >= {floor}"),
        ],
    );
    assert_eq!(counted.code, 0, "the count must be served: {}", counted.err);
    counted.rows()[0]["reaching"].as_i64().expect("a count")
}

/// A call is treated as a change, and an unconfirmed one is never sent.
///
/// # Why this holds even for a routine that only counts
///
/// The routine used here writes nothing. That is not something the product
/// knows, and it is the whole point: it cannot read the body, so it cannot tell
/// this call from one that empties a table. Refusing both is the only answer
/// that is right in the case that matters. A product that decided by the name,
/// or by what the call looked like, would let the dangerous one through on the
/// day somebody renamed it.
///
/// FR-077. The call is made without the mark of confirmation and asserted to
/// end in the number the annex gives an unconfirmed change, carrying the same
/// identifier any other unconfirmed change carries.
#[test]
fn a_call_is_treated_as_a_change_and_an_unconfirmed_one_is_never_sent() {
    let Some(dsn) = destination_or_skip("refusing an unconfirmed call to a routine") else {
        return;
    };
    let sandbox = Sandbox::new();

    let refused = on_server(
        &sandbox,
        &dsn,
        &["query", "call", ROUTINE, "--param", "0", "--param", "0"],
    );
    assert_eq!(
        refused.code, 3,
        "an unconfirmed call must be refused: {} {}",
        refused.out, refused.err
    );
    assert_eq!(refused.code(), "safety.unconfirmed");
    assert!(
        refused.out.trim().is_empty(),
        "a refused call left something on the channel that carries data: {}",
        refused.out
    );
}

/// A call answers with its result sets, each one kept apart from the others.
///
/// # Why the shape is asserted and not only the value
///
/// Because the failure this guards against is folding: several answers arriving
/// as one, with no way for a caller to tell where the first ends and the second
/// begins. That is invisible when a routine happens to answer once, which is
/// why the number of sets, the position of each and the columns of each are all
/// asserted rather than just the value inside.
///
/// FR-062. The call is made with the values its signature takes and asserted to
/// come back with its sets counted, each carrying its own position and its own
/// columns. A routine nobody stored is asserted to be reported as an absence,
/// and a call whose number of values does not match the signature is asserted
/// to be refused rather than sent as if it matched.
#[test]
fn a_call_answers_with_its_result_sets_each_one_kept_apart() {
    let Some(dsn) = destination_or_skip("calling a routine and reading its result sets") else {
        return;
    };
    let sandbox = Sandbox::new();

    let listed = on_server(&sandbox, &dsn, &["schema", "routines"]);
    assert_eq!(
        listed.code, 0,
        "the routines must be listed: {}",
        listed.err
    );
    assert!(
        listed
            .rows()
            .iter()
            .any(|row| row["name"].as_str() == Some(ROUTINE)),
        "the declared destination does not carry the routine `{ROUTINE}` this proof calls"
    );

    let called = on_server(
        &sandbox,
        &dsn,
        &[
            "--yes", "query", "call", ROUTINE, "--param", "0", "--param", "0",
        ],
    );
    assert_eq!(called.code, 0, "the call must be served: {}", called.err);

    let data = called.answer()["data"].clone();
    assert_eq!(data["routine"], ROUTINE, "the answer names another routine");
    let sets = data["sets"].as_array().expect("the sets, in order").clone();
    assert_eq!(
        data["set_count"],
        serde_json::json!(sets.len()),
        "the number of sets reported is not the number of sets carried: {data}"
    );
    assert!(
        !sets.is_empty(),
        "the call answered with nothing at all: {data}"
    );
    for (position, set) in sets.iter().enumerate() {
        assert_eq!(
            set["set"],
            serde_json::json!(position + 1),
            "a set is not in the position it claims: {set}"
        );
        assert!(
            set["columns"]
                .as_array()
                .is_some_and(|held| !held.is_empty()),
            "a set arrived with no columns of its own: {set}"
        );
    }

    // A routine nobody stored is an absence, not a failure of the server.
    let missing = on_server(
        &sandbox,
        &dsn,
        &[
            "--yes",
            "query",
            "call",
            "rotina_que_ninguem_guardou",
            "--param",
            "1",
        ],
    );
    assert_eq!(
        missing.code, 8,
        "calling a routine nobody stored must be reported as an absence: {}",
        missing.out
    );
    assert_eq!(missing.code(), "absence.unknown_object");

    // A number of values the signature does not take is refused, and the
    // refusal says so rather than leaving the caller to guess.
    let mismatched = on_server(
        &sandbox,
        &dsn,
        &["--yes", "query", "call", ROUTINE, "--param", "0"],
    );
    assert_ne!(
        mismatched.code, 0,
        "a call whose values do not match the signature must not succeed: {}",
        mismatched.out
    );
    assert!(
        mismatched.failure()["error"]["message"]
            .as_str()
            .is_some_and(|text| text.contains("arguments")),
        "the refusal does not say the number of values was wrong: {}",
        mismatched.failure()
    );
}

/// A routine that answers only through an output value still answers.
///
/// # Why the value is compared against a second reading
///
/// A number that came back is not evidence that it came from the routine. It
/// could be an echo of what was sent, or a leftover, or a zero that happens to
/// be right. So the same question is put to the server directly, and the two
/// have to agree; and then a floor no order reaches is used, so the answer has
/// to move. A value that agreed with the direct count on both floors could not
/// be an echo of the argument, because the argument changed and so did it.
///
/// FR-137. The routine answers through an output parameter and never through a
/// row of its own, and its answer is asserted equal to the count the same
/// question gives when asked directly, for two different floors.
#[test]
fn a_routine_that_answers_only_through_an_output_value_still_answers() {
    let Some(dsn) = destination_or_skip("reading the value a routine returns by parameter") else {
        return;
    };
    let sandbox = Sandbox::new();

    let answered = |floor: &str| {
        let called = on_server(
            &sandbox,
            &dsn,
            &[
                "--yes", "query", "call", ROUTINE, "--param", floor, "--param", "0",
            ],
        );
        assert_eq!(called.code, 0, "the call must be served: {}", called.err);
        let sets = called.answer()["data"]["sets"].clone();
        let held = sets
            .as_array()
            .and_then(|sets| sets.first().cloned())
            .unwrap_or_else(|| panic!("the call returned no value at all: {}", called.answer()));
        held["rows"][0]["how_many"]
            .as_i64()
            .unwrap_or_else(|| panic!("the returned value is not a number: {held}"))
    };

    // A floor every order reaches, and one no order reaches. Both are compared
    // against the same question asked in the ordinary way.
    let reachable = orders_reaching(&sandbox, &dsn, "0");
    assert!(
        reachable > 0,
        "the destination carries no orders, so this proof cannot tell a real answer \
         from a zero"
    );
    assert_eq!(
        answered("0"),
        reachable,
        "the value returned by parameter does not agree with the direct count"
    );

    let unreachable = orders_reaching(&sandbox, &dsn, "99999999");
    assert_eq!(
        answered("99999999"),
        unreachable,
        "the value returned by parameter did not follow the argument it was given"
    );
    assert_ne!(
        reachable, unreachable,
        "both floors give the same count, so the value could be ignoring the argument"
    );
}