#[allow(dead_code)]
mod support;
use support::server::{destination_or_skip, on_server, unique_mark};
use support::{Outcome, Sandbox};
fn own_table() -> String {
format!("shop.flow_{}", unique_mark())
}
fn build(sandbox: &Sandbox, dsn: &str, table: &str) {
let made = on_server(
sandbox,
dsn,
&[
"--yes",
"query",
"run",
&format!("CREATE TABLE {table} (id INT PRIMARY KEY, label VARCHAR(64))"),
],
);
assert_eq!(made.code, 0, "building `{table}`: {}", made.err);
}
struct Owned<'a> {
sandbox: &'a Sandbox,
dsn: String,
name: String,
}
impl<'a> Owned<'a> {
fn built(sandbox: &'a Sandbox, dsn: &str) -> Self {
let claimed = Self::claimed(sandbox, dsn);
build(sandbox, dsn, &claimed.name);
claimed
}
fn claimed(sandbox: &'a Sandbox, dsn: &str) -> Self {
Self {
sandbox,
dsn: dsn.to_owned(),
name: own_table(),
}
}
}
impl Drop for Owned<'_> {
fn drop(&mut self) {
let removed = on_server(
self.sandbox,
&self.dsn,
&[
"--yes",
"query",
"run",
&format!("DROP TABLE IF EXISTS {}", self.name),
],
);
support::server::confirm_removed(&removed, &format!("the table {}", self.name));
}
}
fn fill(sandbox: &Sandbox, dsn: &str, statement: &str) -> Outcome {
let written = on_server(
sandbox,
dsn,
&["--yes", "query", "tx", "--statement", statement],
);
assert_eq!(written.code, 0, "writing rows: {}", written.err);
written
}
fn signature(sandbox: &Sandbox, dsn: &str, table: &str) -> String {
let read = on_server(
sandbox,
dsn,
&[
"--checksum",
"query",
"run",
&format!("SELECT id, label FROM {table} ORDER BY id"),
],
);
assert_eq!(read.code, 0, "reading `{table}`: {}", read.err);
read.answer()["checksum"]
.as_str()
.unwrap_or_else(|| panic!("the read must carry a signature: {}", read.out))
.to_owned()
}
#[test]
fn a_simulated_change_predicts_its_effect_and_changes_nothing() {
let Some(dsn) = destination_or_skip("simulating a change without applying it") else {
return;
};
let sandbox = Sandbox::new();
let owned = Owned::built(&sandbox, &dsn);
let table = owned.name.clone();
fill(
&sandbox,
&dsn,
&format!("INSERT INTO {table} (id, label) VALUES (1, 'um'), (2, 'dois'), (3, 'tres')"),
);
let before = signature(&sandbox, &dsn, &table);
let simulated = on_server(
&sandbox,
&dsn,
&[
"--yes",
"--dry-run",
"query",
"run",
&format!("DELETE FROM {table} WHERE id > 1"),
],
);
assert_eq!(simulated.code, 0, "the simulation runs: {}", simulated.err);
let answer = simulated.answer();
assert_eq!(
answer["data"]["simulated"],
serde_json::json!(true),
"the answer has to say it was a simulation: {answer}"
);
assert_eq!(
answer["data"]["predicted_rows"],
serde_json::json!(2),
"two rows match the restriction, and the prediction has to say so: {answer}"
);
let after = signature(&sandbox, &dsn, &table);
assert_eq!(
before, after,
"the simulation changed the table it was only supposed to describe"
);
}
#[test]
fn a_simulation_of_a_refused_statement_reports_the_refusal() {
let Some(dsn) = destination_or_skip("simulating a statement the validation refuses") else {
return;
};
let sandbox = Sandbox::new();
let refused = on_server(
&sandbox,
&dsn,
&["--yes", "--dry-run", "query", "run", "DELETE FROM WHERE"],
);
assert_ne!(refused.code, 0, "an unreadable statement is not a success");
assert_eq!(
refused.failure()["error"]["category"],
"validation",
"the simulation has to answer with the validation's own refusal: {}",
refused.err
);
assert!(
refused.out.is_empty(),
"a failure never reaches the primary channel"
);
}
#[test]
fn a_value_shaped_like_an_injection_stays_one_value() {
let Some(dsn) = destination_or_skip("binding a value that looks like an injection") else {
return;
};
let sandbox = Sandbox::new();
let owned = Owned::built(&sandbox, &dsn);
let table = owned.name.clone();
let dangerous = "O'Brien'; DROP TABLE clientes; --";
let echoed = on_server(
&sandbox,
&dsn,
&["query", "run", "SELECT ? AS valor", "--param", dangerous],
);
assert_eq!(echoed.code, 0, "the value is bound: {}", echoed.err);
assert_eq!(
echoed.rows()[0]["valor"],
serde_json::json!(dangerous),
"the value came back changed, so something read it as statement text"
);
let written = on_server(
&sandbox,
&dsn,
&[
"--yes",
"query",
"tx",
"--statement",
&format!("INSERT INTO {table} (id, label) VALUES (1, {dangerous:?})"),
],
);
assert_eq!(written.code, 0, "writing the row: {}", written.err);
let still_there = on_server(
&sandbox,
&dsn,
&[
"query",
"run",
&format!("SELECT COUNT(*) AS n FROM {table}"),
],
);
assert_eq!(
still_there.rows()[0]["n"],
serde_json::json!(1),
"the table lost its row, so the punctuation was obeyed as a statement"
);
}
#[test]
fn a_statement_read_from_the_input_answers_exactly_as_an_argument_does() {
let Some(dsn) = destination_or_skip("reading the statement from the standard input") else {
return;
};
let sandbox = Sandbox::new();
let statement = "SELECT 1 AS um, 'dois' AS texto";
let as_argument = on_server(&sandbox, &dsn, &["query", "run", statement]);
assert_eq!(as_argument.code, 0, "{}", as_argument.err);
let mut command = assert_cmd::Command::cargo_bin("mariadb-cli").expect("the binary is built");
let finished = command
.arg("--config-dir")
.arg(sandbox.path())
.args(["--dsn", &dsn, "query", "run", "--stdin"])
.write_stdin(statement)
.output()
.expect("the binary runs");
assert_eq!(
finished.status.code(),
Some(as_argument.code),
"the two channels must end the same way"
);
assert_eq!(
String::from_utf8_lossy(&finished.stdout),
as_argument.out,
"the same statement by two channels must answer with the same bytes"
);
}
#[test]
fn asking_for_the_count_alone_agrees_with_the_whole_read() {
let Some(dsn) = destination_or_skip("counting without carrying the rows") else {
return;
};
let sandbox = Sandbox::new();
let owned = Owned::built(&sandbox, &dsn);
let table = owned.name.clone();
fill(
&sandbox,
&dsn,
&format!(
"INSERT INTO {table} (id, label) VALUES (1, 'um'), (2, 'dois'), (3, 'tres'), \
(4, 'quatro')"
),
);
let read = format!("SELECT id, label FROM {table} ORDER BY id");
let whole = on_server(&sandbox, &dsn, &["query", "run", &read]);
let counted = on_server(&sandbox, &dsn, &["--count-only", "query", "run", &read]);
assert_eq!(whole.code, 0, "{}", whole.err);
assert_eq!(counted.code, 0, "{}", counted.err);
let rows = whole.rows();
assert_eq!(rows.len(), 4, "the table was filled with four rows");
let answer = counted.answer();
assert_eq!(
answer["data"]["count"],
serde_json::json!(rows.len()),
"the count has to be the number of rows the whole read returned: {answer}"
);
assert!(
answer["data"]["rows"].is_null(),
"asking for the count alone must carry no rows: {answer}"
);
}
#[test]
fn asking_the_count_of_a_change_is_refused_before_the_change_happens() {
let Some(dsn) = destination_or_skip("refusing a count of a change") else {
return;
};
let sandbox = Sandbox::new();
let owned = Owned::built(&sandbox, &dsn);
let table = owned.name.clone();
fill(
&sandbox,
&dsn,
&format!("INSERT INTO {table} (id, label) VALUES (1, 'um'), (2, 'dois')"),
);
let change = format!("UPDATE {table} SET label = 'trocado'");
let refused = on_server(
&sandbox,
&dsn,
&["--count-only", "--yes", "query", "run", &change],
);
assert_eq!(
refused.code, 2,
"the requirement publishes the usage number for this combination: {}",
refused.out
);
assert_eq!(
refused.code(),
"usage.count_of_a_change",
"the refusal must name the combination it refuses: {}",
refused.out
);
let ordered = format!("SELECT label FROM {table} ORDER BY id");
let after = on_server(&sandbox, &dsn, &["query", "run", &ordered]);
assert_eq!(after.code, 0, "{}", after.err);
let labels: Vec<String> = after
.rows()
.iter()
.map(|row| row["label"].as_str().unwrap_or_default().to_owned())
.collect();
assert_eq!(
labels,
vec!["um".to_owned(), "dois".to_owned()],
"the change must not have happened: {}",
after.out
);
}
#[test]
fn a_change_separates_what_it_matched_from_what_it_altered() {
let Some(dsn) = destination_or_skip("separating matched rows from altered rows") else {
return;
};
let sandbox = Sandbox::new();
let owned = Owned::built(&sandbox, &dsn);
let table = owned.name.clone();
fill(
&sandbox,
&dsn,
&format!("INSERT INTO {table} (id, label) VALUES (1, 'um')"),
);
let idle = format!("UPDATE {table} SET label = 'um' WHERE id = 1");
let matched = on_server(
&sandbox,
&dsn,
&[
"--yes",
"--row-count",
"matched",
"query",
"tx",
"--statement",
&idle,
],
);
let changed = on_server(
&sandbox,
&dsn,
&[
"--yes",
"--row-count",
"changed",
"query",
"tx",
"--statement",
&idle,
],
);
assert_eq!(matched.code, 0, "{}", matched.err);
assert_eq!(changed.code, 0, "{}", changed.err);
let under_matched = &matched.answer()["data"]["rows"][0]["rows"];
assert_eq!(
under_matched["matched"],
serde_json::json!(1),
"the restriction matched the row: {under_matched}"
);
assert_eq!(
under_matched["changed"],
serde_json::json!(0),
"the row already held that value, so nothing was altered: {under_matched}"
);
assert_eq!(under_matched["requested"], serde_json::json!("matched"));
assert_eq!(
under_matched["affected"],
serde_json::json!(1),
"the number handed over has to be the one that was asked for: {under_matched}"
);
let under_changed = &changed.answer()["data"]["rows"][0]["rows"];
assert_eq!(under_changed["matched"], serde_json::json!(1));
assert_eq!(under_changed["changed"], serde_json::json!(0));
assert_eq!(under_changed["requested"], serde_json::json!("changed"));
assert_eq!(
under_changed["affected"],
serde_json::json!(0),
"asking for what was altered must not hand over what was matched: {under_changed}"
);
}
#[test]
fn a_statement_of_structure_inside_a_block_always_warns_that_it_escaped() {
let Some(dsn) = destination_or_skip("warning that a definition escapes the block") else {
return;
};
let sandbox = Sandbox::new();
let owned = Owned::claimed(&sandbox, &dsn);
let table = owned.name.clone();
let block = on_server(
&sandbox,
&dsn,
&[
"--yes",
"query",
"tx",
"--statement",
"SELECT 1",
"--statement",
&format!("CREATE TABLE {table} (id INT PRIMARY KEY)"),
],
);
assert_eq!(block.code, 0, "the block finishes: {}", block.err);
let answer = block.answer();
assert_eq!(
answer["data"]["confirmed"],
serde_json::json!(true),
"the block was confirmed: {answer}"
);
let gaps = answer["gaps"]
.as_array()
.unwrap_or_else(|| panic!("the definition has to be declared: {answer}"));
assert_eq!(gaps.len(), 1, "one statement escaped, so one gap: {answer}");
assert_eq!(
gaps[0]["cause"],
serde_json::json!("escapes_atomic_block"),
"the gap has to name the escape: {answer}"
);
let ordinary = on_server(
&sandbox,
&dsn,
&[
"--yes",
"query",
"tx",
"--statement",
"SELECT 1",
"--statement",
"SELECT 2",
],
);
assert_eq!(ordinary.code, 0, "{}", ordinary.err);
assert!(
ordinary.answer()["gaps"].is_null(),
"nothing escaped this block, so nothing may say it did: {}",
ordinary.out
);
}
#[test]
fn a_change_that_was_never_confirmed_fails_at_once_rather_than_asking() {
let Some(dsn) = destination_or_skip("refusing to ask when asking is forbidden") else {
return;
};
let sandbox = Sandbox::new();
let owned = Owned::built(&sandbox, &dsn);
let table = owned.name.clone();
fill(
&sandbox,
&dsn,
&format!("INSERT INTO {table} (id, label) VALUES (1, 'um')"),
);
let statement = format!("DELETE FROM {table} WHERE id = 1");
let unconfirmed = on_server(&sandbox, &dsn, &["--no-input", "query", "run", &statement]);
assert_eq!(
unconfirmed.code, 3,
"an unconfirmed change is refused, not asked about: {}",
unconfirmed.err
);
assert_eq!(
unconfirmed.code(),
"safety.unconfirmed",
"the refusal has to name the missing confirmation: {}",
unconfirmed.err
);
assert!(
unconfirmed.out.is_empty(),
"a failure never reaches the primary channel"
);
let confirmed = on_server(
&sandbox,
&dsn,
&["--no-input", "--yes", "query", "run", &statement],
);
assert_eq!(
confirmed.code, 0,
"the same change, confirmed, has to run under the same mark: {}",
confirmed.err
);
}
#[test]
fn an_empty_separator_is_refused_before_the_file_is_opened() {
let Some(dsn) = destination_or_skip("refusing a separator that separates nothing") else {
return;
};
let sandbox = Sandbox::new();
let refused = on_server(
&sandbox,
&dsn,
&[
"--yes",
"query",
"file",
"/caminho/que/nao/existe/rotina.sql",
"--delimiter",
"",
],
);
assert_eq!(refused.code, 2, "incorrect use exits two: {}", refused.err);
assert_eq!(
refused.code(),
"usage.empty_delimiter",
"a missing file must not be what this run reports: {}",
refused.err
);
assert!(
refused.out.is_empty(),
"a failure never reaches the primary channel"
);
}