#[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};
const WRITABLE: &str = "bulk";
const WRITTEN_COMMENT: &str = "uma nota que o mapa nao deve carregar";
const COMPRESSION: usize = 10;
fn writable(proof: &str) -> Option<String> {
destination_or_skip(proof).map(|dsn| aimed_at(&dsn, WRITABLE))
}
struct Fixture<'a> {
sandbox: &'a Sandbox,
dsn: String,
undo: Vec<String>,
}
impl<'a> Fixture<'a> {
fn new(sandbox: &'a Sandbox, dsn: &str) -> Self {
Self {
sandbox,
dsn: dsn.to_owned(),
undo: Vec::new(),
}
}
fn run(&self, args: &[&str]) -> Outcome {
on_server(self.sandbox, &self.dsn, args)
}
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);
}
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) {
for undo in self.undo.iter().rev() {
let removed = self.run(&["--yes", "query", "run", undo]);
support::server::confirm_removed(&removed, undo);
}
}
}
fn row_where<'a>(rows: &'a [Value], field: &str, value: &str) -> &'a Value {
rows.iter()
.find(|row| row[field] == value)
.unwrap_or_else(|| panic!("no row carries `{value}` under `{field}`: {rows:?}"))
}
fn listed(row: &Value, field: &str) -> Vec<String> {
row[field]
.as_array()
.map(|held| {
held.iter()
.filter_map(|one| one.as_str().map(ToOwned::to_owned))
.collect()
})
.unwrap_or_default()
}
const PLAIN_COLUMNS: usize = 20;
fn plain_columns() -> String {
(0..PLAIN_COLUMNS)
.map(|at| format!("plain_{at:02} VARCHAR(40)"))
.collect::<Vec<_>>()
.join(", ")
}
fn linked_pair(fixture: &mut Fixture) -> (String, String) {
let parent = format!("map_parent_{}", unique_mark());
let child = format!("map_child_{}", unique_mark());
let plain = plain_columns();
fixture.build(
&format!(
"CREATE TABLE {parent} (\
id INT PRIMARY KEY, \
label VARCHAR(20) UNIQUE, \
note VARCHAR(40) COMMENT '{WRITTEN_COMMENT}', {plain})"
),
format!("DROP TABLE IF EXISTS {parent}"),
);
fixture.build(
&format!(
"CREATE TABLE {child} (\
cid INT PRIMARY KEY, pid INT, {plain}, \
FOREIGN KEY (pid) REFERENCES {parent}(id))"
),
format!("DROP TABLE IF EXISTS {child}"),
);
(parent, child)
}
fn link_the_server_holds(fixture: &Fixture, child: &str, parent: &str) -> String {
let referenced = fixture.run(&["schema", "keys", "--table", child]);
assert_eq!(
referenced.code, 0,
"the references must be served: {}",
referenced.err
);
let rows = referenced.rows();
let reference = rows.first().expect("the server holds the link just built");
assert_eq!(
reference["referenced_table"],
Value::from(parent),
"the server must hold the link this proof built"
);
format!(
"{}->{WRITABLE}.{}.{}",
reference["column"].as_str().unwrap_or_default(),
reference["referenced_table"].as_str().unwrap_or_default(),
reference["referenced_column"].as_str().unwrap_or_default()
)
}
fn full_description_bytes(fixture: &Fixture, rows: &[Value], owned: &[&str]) -> usize {
let mut whole = 0;
for row in rows {
let named = row["name"].as_str().unwrap_or_default();
assert!(
!named.is_empty(),
"a map row names nothing, so the comparison below would measure \
zero and pass for the wrong reason: {row}"
);
let bare = named.rsplit_once('.').map_or(named, |(_, last)| last);
let full = fixture.run(&["schema", "columns", "--table", bare, "--detail", "full"]);
if full.code == 0 {
whole += full.out.len();
continue;
}
assert!(
!owned.contains(&bare),
"the full description of `{bare}` must be served: {}",
full.err
);
}
whole
}
#[test]
fn fr_020_the_compact_map_carries_the_shape_the_server_reports_and_stays_small() {
let Some(dsn) = writable("the compact map of a real database") else {
return;
};
let sandbox = Sandbox::new();
let mut fixture = Fixture::new(&sandbox, &dsn);
let (parent, child) = linked_pair(&mut fixture);
let mapped = fixture.run(&["schema", "map"]);
assert_eq!(mapped.code, 0, "the map must be served: {}", mapped.err);
let rows = mapped.rows();
let described = fixture.run(&["schema", "columns", "--table", &parent]);
assert_eq!(
described.code, 0,
"the description must be served: {}",
described.err
);
let described_rows = described.rows();
assert_eq!(
row_where(&described_rows, "name", "id")["key"],
Value::from("PRI"),
"the server must declare the first column as the primary key"
);
assert_eq!(
row_where(&described_rows, "name", "label")["key"],
Value::from("UNI"),
"the server must declare the second column as unique"
);
let mapped_parent = row_where(&rows, "name", &format!("{WRITABLE}.{parent}"));
let keys = listed(mapped_parent, "keys");
assert!(
keys.contains(&"id:PRI".to_owned()) && keys.contains(&"label:UNI".to_owned()),
"the map must carry the key marks the server declared, and carried {keys:?}"
);
let expected_link = link_the_server_holds(&fixture, &child, &parent);
let links = listed(
row_where(&rows, "name", &format!("{WRITABLE}.{child}")),
"links",
);
assert!(
links.contains(&expected_link),
"the map must carry the link the server holds, `{expected_link}`, and carried {links:?}"
);
assert!(
!mapped.out.contains("varchar"),
"the map must not carry the full type: {}",
mapped.out
);
assert!(
!mapped.out.contains(WRITTEN_COMMENT),
"the map must not carry the comment: {}",
mapped.out
);
let whole = full_description_bytes(&fixture, &rows, &[&parent, &child]);
let compact = mapped.out.len();
assert!(
compact * COMPRESSION <= whole,
"the map is {compact} bytes against {whole} of full description, \
which is under the {COMPRESSION} times the requirement states"
);
}
#[test]
fn fr_022_a_read_the_server_answered_carries_its_names_and_its_values() {
let Some(dsn) = writable("a read the server answered") else {
return;
};
let sandbox = Sandbox::new();
let mut fixture = Fixture::new(&sandbox, &dsn);
let table = format!("read_rows_{}", unique_mark());
fixture.build(
&format!("CREATE TABLE {table} (id INT PRIMARY KEY, label VARCHAR(20))"),
format!("DROP TABLE IF EXISTS {table}"),
);
fixture.fill(&format!(
"INSERT INTO {table} VALUES (1, 'um'), (2, 'dois'), (3, 'tres')"
));
let statement = format!("SELECT id, label FROM {WRITABLE}.{table} ORDER BY id");
let read = fixture.run(&["query", "run", &statement]);
assert_eq!(read.code, 0, "the read must be served: {}", read.err);
let answer = read.answer();
assert_eq!(
answer["data"]["columns"],
Value::from(vec!["id", "label"]),
"the answer must carry the names the server labelled the columns with"
);
let rows = read.rows();
assert_eq!(rows.len(), 3, "three rows were written: {}", read.out);
assert_eq!(answer["data"]["row_count"], 3);
for (at, (number, text)) in [(1, "um"), (2, "dois"), (3, "tres")]
.into_iter()
.enumerate()
{
assert_eq!(
rows[at]["id"],
Value::from(number),
"the whole number the server holds must arrive as it is"
);
assert_eq!(
rows[at]["label"],
Value::from(text),
"the text the server holds must arrive as it is"
);
}
let refused = fixture.run(&[
"query",
"run",
&format!("{statement}; SELECT COUNT(*) FROM {WRITABLE}.{table}"),
]);
assert_eq!(
refused.code, 3,
"two statements in one call must be refused: {}",
refused.err
);
assert_eq!(refused.code(), "sql.multiple_statements");
let again = fixture.run(&["query", "run", &statement]);
assert_eq!(
again.code, 0,
"the read must still be served: {}",
again.err
);
assert_eq!(
again.rows().len(),
3,
"the refused call reached the destination anyway"
);
}