mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Data leaving for a real table and coming back from one.
//!
//! # Why these proofs sit together
//!
//! Both are the half of Proof 7 that only a table can answer. A file reader can
//! be asked what it does with a malformed line without any server at all, and
//! that half lives in `acceptance_local_data.rs`. What it cannot answer is what
//! a written copy holds when it is loaded back somewhere else, and what a load
//! aimed at a name no table carries does instead of reporting success.
//!
//! What a real column refuses is the other failure a round trip has, and it
//! moved to `acceptance_server_load_refusals.rs` when this file crossed the
//! project's ceiling. Those proofs share a fixture and a cleanup with each
//! other; these two share a fixture with each other.
//!
//! Both build their own table, fill it, read it, and remove it afterwards, so
//! two runs against the same server never meet each other's rows and a red here
//! is about the round trip rather than about whoever else is using the server.
//!
//! Both are gated behind a declared destination and say out loud that they were
//! skipped, with the reason.

// 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::json;
use support::server::{
    aimed_at, confirm_removed, destination_or_skip, on_server, own_identifier_base, unique_mark,
};
use support::Sandbox;

/// What the round trip lays down on the server, removed however the proof ends.
///
/// # Why a guard and not a removal at the end
///
/// It used to be a removal at the end, with seven assertions standing between
/// the table being built and being taken away. Any of the seven failing left
/// the table on a server other people share, which is the same defect already
/// recorded against another file of this suite and fixed there the same way.
///
/// Both objects sit in one guard because both belong to one round trip. They
/// go in the reverse of the order they arrive, so the copy is gone before the
/// table it was copied from.
///
/// Each name is removed `IF EXISTS`, because the guard is armed before either
/// object is laid down — which is the whole point, since the building itself
/// can fail.
struct Built<'a> {
    sandbox: &'a Sandbox,
    dsn: String,
    table: String,
    twin: String,
}

impl Drop for Built<'_> {
    fn drop(&mut self) {
        // 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 (statement, what) in [
            (
                format!("DROP DATABASE IF EXISTS {}", self.twin),
                format!("the database {}", self.twin),
            ),
            (
                format!("DROP TABLE IF EXISTS shop.{}", self.table),
                format!("the table shop.{}", self.table),
            ),
        ] {
            let removed = on_server(
                self.sandbox,
                &self.dsn,
                &["--yes", "query", "run", &statement],
            );
            confirm_removed(&removed, &what);
        }
    }
}

// ---------------------------------------------------------------------------
// Proof 7 — data goes out and comes back without loss
// ---------------------------------------------------------------------------

/// Creates this run's own source table and fills it through the load itself.
///
/// Kept apart from the round trip it serves. Everything here has to work
/// before that proof begins, and reading it inline buried the handful of
/// assertions the requirement is really about under fifty lines of setting up.
fn seeded_source(sandbox: &Sandbox, dsn: &str, scratch: &std::path::Path, table: &str) {
    let built = on_server(
        sandbox,
        dsn,
        &[
            "--yes",
            "query",
            "run",
            &format!(
                "CREATE TABLE shop.{table} (id INT NOT NULL PRIMARY KEY, \
                 customer VARCHAR(80) NOT NULL, total DECIMAL(10,2) NOT NULL, \
                 placed_at DATETIME NOT NULL, note TEXT NULL)"
            ),
        ],
    );
    assert_eq!(built.code, 0, "the source must be created: {}", built.err);

    // Filled through the load rather than through a written statement, because
    // the load is the path that confirms what it wrote. What this proof is
    // about starts at the copy, so how the rows got there is scaffolding and
    // has to be the surest path available rather than the shortest.
    let seed = scratch.join("semente.csv");
    std::fs::write(
        &seed,
        "id,customer,total,placed_at,note\n\
         1,ana,10.50,2026-01-01 10:00:00,com nota\n\
         2,bea,0.00,2026-01-02 11:30:00,sem nota\n\
         3,cid,999999.99,2026-01-03 12:45:00,acentuação e cedilha\n\
         4,dan,-7.25,2026-01-04 23:59:59,fim\n",
    )
    .expect("the seed is written");

    let filled = on_server(
        sandbox,
        dsn,
        &[
            "--yes",
            "data",
            "import",
            "--file",
            seed.to_str().expect("a utf8 path"),
            "--table",
            table,
            "--header",
        ],
    );
    assert_eq!(filled.code, 0, "the source must be filled: {}", filled.err);
    assert_eq!(
        filled.answer()["data"]["rows_written"],
        json!(4),
        "every seeded row must be kept: {}",
        filled.out
    );
}

/// A table written out and read back keeps every row.
///
/// # Why the twin is a whole database and not a renamed table
///
/// The copy names the table it came from, so reading it back anywhere else
/// would mean editing the product's own output first, and a round trip that
/// rewrites the file in the middle proves nothing about the file. An empty
/// database of its own leaves the copy untouched: the same bytes the product
/// wrote are the bytes it reads, and the twin starts with nothing in it.
///
/// The rows are compared whole rather than counted, because a count survives a
/// column arriving empty and the promise is about the row.
///
/// # Why the source is a table of this run's own
///
/// The obvious source is the sample table everyone reads, and that is exactly
/// why it cannot be used: anything else running against the same server may be
/// adding to it, emptying it or holding it, and this proof would then be
/// measuring that instead. A table this run creates, fills, copies and removes
/// is answerable to nobody else, so a red here is about the round trip.
///
/// FR-114. The copy is written, declares the same number of rows the table
/// holds, is loaded into an empty database, and the rows read back are compared
/// whole against the ones that went out.
///
/// FR-115. The source is filled through the load itself, which must report every
/// seeded row as written — the count before and after being what makes the rest
/// of the proof about the copy rather than about the fill.
#[test]
fn rows_written_out_match_the_rows_read_back() {
    let Some(dsn) = destination_or_skip("writing a table out and loading it back") else {
        return;
    };
    let sandbox = Sandbox::new();
    let scratch = tempfile::tempdir().expect("a scratch directory");
    let copy = scratch.path().join("copia.sql");
    let copy_path = copy.to_str().expect("a utf8 path").to_owned();
    let mark = unique_mark();
    let table = format!("round_trip_{mark}");
    let twin = format!("shop_twin_{mark}");

    // Armed before anything is laid down, so that a failure while the source is
    // being built and filled takes the table with it rather than leaving it.
    let _built = Built {
        sandbox: &sandbox,
        dsn: dsn.clone(),
        table: table.clone(),
        twin: twin.clone(),
    };

    seeded_source(&sandbox, &dsn, scratch.path(), &table);

    let source = on_server(
        &sandbox,
        &dsn,
        &[
            "query",
            "run",
            &format!("SELECT * FROM shop.{table} ORDER BY id"),
        ],
    );
    assert_eq!(
        source.code, 0,
        "the source must be readable: {}",
        source.err
    );
    let original = source.rows();
    assert_eq!(
        original.len(),
        4,
        "the source must hold every row it was given"
    );

    let written = on_server(
        &sandbox,
        &dsn,
        &["data", "export", "--table", &table, "--to", &copy_path],
    );
    assert_eq!(written.code, 0, "the copy must be written: {}", written.err);
    assert_eq!(
        written.answer()["data"]["rows"],
        json!(original.len()),
        "the copy declares a different number of rows than the table holds"
    );

    let made = on_server(
        &sandbox,
        &dsn,
        &["--yes", "query", "run", &format!("CREATE DATABASE {twin}")],
    );
    assert_eq!(made.code, 0, "the empty twin must be created: {}", made.err);

    let inside_twin = aimed_at(&dsn, &twin);
    let loaded = on_server(
        &sandbox,
        &inside_twin,
        &["--yes", "query", "file", &copy_path],
    );
    let read_back = on_server(
        &sandbox,
        &inside_twin,
        &[
            "query",
            "run",
            &format!("SELECT * FROM {twin}.{table} ORDER BY id"),
        ],
    );
    assert_eq!(loaded.code, 0, "the copy must load: {}", loaded.err);
    assert_eq!(
        read_back.code, 0,
        "the twin must be readable: {}",
        read_back.err
    );
    let kept = read_back.rows();
    assert_eq!(
        kept.len(),
        original.len(),
        "the twin holds a different number of rows"
    );
    assert_eq!(
        kept, original,
        "a row changed between going out and coming back"
    );

    // Neither removal is asserted here any more. Both now happen in the guard,
    // which runs whether this proof ends by passing or by unwinding, and which
    // raises on a removal that failed unless a failure is already on its way.
}

/// FR-115. A load into a table that is not there ends in refusal, not in zero.
///
/// # The defect this was written from
///
/// The skip policy caught every refusal the server gave, whatever it was about.
/// Loading into a name no table carries read the whole file, wrote nothing,
/// recorded one rejection per row saying "the named object does not exist", and
/// ended in 0. An agent reads the exit code, so it was told the load worked.
///
/// FR-115 scopes that policy to one thing: "a row does not match a type". A
/// missing table is not a property of any row — it is one precondition that
/// failed once, reported N times at a severity that cost the exit code. Its
/// sibling `data export` already answered the same condition with 8.
///
/// # Why the sibling is asserted here too
///
/// The defect was invisible while each command was read on its own. It only
/// exists between them, so the proof holds them side by side: whatever the two
/// answer, they have to answer the same thing to the same missing table.
#[test]
fn a_load_into_a_missing_table_is_refused_the_way_a_read_of_one_is() {
    let Some(dsn) = destination_or_skip("refusing a load into a table that is absent") else {
        return;
    };
    let sandbox = Sandbox::new();
    let scratch = tempfile::tempdir().expect("a scratch directory");
    let file = scratch.path().join("linhas.csv");
    std::fs::write(&file, "id\n1\n2\n").expect("the file is written");

    // Of this run alone, so nothing can make it exist by accident.
    let absent = format!("nao_existe_{}", own_identifier_base());

    let loaded = on_server(
        &sandbox,
        &dsn,
        &[
            "--yes",
            "data",
            "import",
            "--file",
            file.to_str().expect("a utf8 path"),
            "--table",
            &absent,
            "--header",
            // Written out, though `data.stop_on_refusal` defaults to skipping
            // and would reach the same path. The defect this proof exists for
            // is the skip policy swallowing a structural refusal, and a proof
            // that exercises that policy only because a key in another file
            // happens to default that way stops exercising it the day the key
            // changes — while still passing.
            "--on-error",
            "skip",
        ],
    );
    // The exact number and the exact class, not merely "not zero" and "the same
    // as its sibling". An audit built the vacuous pass those two allowed: point
    // the proof at a destination nothing answers on, and both commands come
    // back with `network.unreachable` and 5. Not-zero holds, same-as-each-other
    // holds, and the proof reports success without ever reaching a server to
    // ask about a missing table. On a machine where the destination is declared
    // but momentarily unreachable, that is the whole proof going quiet.
    assert_eq!(
        loaded.code, 8,
        "a load into a table that is absent is the absence class and ends in 8; \
         anything else means this proof never reached the condition it exists \
         for: {}",
        loaded.out
    );
    assert_eq!(
        loaded.failure()["error"]["category"],
        "absence",
        "the load must fail because the table is not there, and not because \
         something else went wrong on the way: {}",
        loaded.out
    );
    // Which absence, and not merely that something was absent. A second vacuous
    // pass sits one level below the one guarded above: point this at a database
    // that does not exist and the session fails on `USE` with condition 1049
    // before a single row is sent. That answers `absence` and 8 exactly as a
    // missing table does, so both assertions above hold while the skip policy —
    // the thing FR-115 scopes and the thing this proof exists to hold — is never
    // consulted at all. The server names the table it could not find in the
    // condition for a missing table and names only the schema in the condition
    // for a missing database, so requiring the table's own name here is what
    // separates the two.
    let causes = loaded.failure()["error"]["causes"].to_string();
    assert!(
        causes.contains(&absent),
        "the refusal must name the absent table, which is what the condition \
         for a missing table carries; a refusal that never names it came from \
         somewhere earlier than the load, and the row policy was never reached: \
         {causes}"
    );

    let read = on_server(
        &sandbox,
        &dsn,
        &[
            "data",
            "export",
            "--to",
            scratch
                .path()
                .join("saida.tsv")
                .to_str()
                .expect("a utf8 path"),
            "--table",
            &absent,
        ],
    );
    assert_eq!(
        loaded.code, read.code,
        "loading into a missing table and reading from one are the same \
         condition, so the two commands must end the same way; load gave {} \
         and read gave {}",
        loaded.code, read.code
    );
    assert_eq!(
        loaded.failure()["error"]["category"],
        read.failure()["error"]["category"],
        "the prose here promises the two answer the same thing, and the number \
         alone is the part that was already fixed; the class has to agree too"
    );
}