#[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 TYPED_SHAPE: &str = "\
n INT, w BIGINT, d DECIMAL(30,10), f DOUBLE, s VARCHAR(30), em VARCHAR(30), \
b BLOB, dt DATETIME(6), ts TIMESTAMP NULL, da DATE, tm TIME, y YEAR, \
bi BIT(8), e ENUM('a','b'), st SET('x','y'), u uuid, a4 inet4, a6 inet6, \
missing INT";
const TYPED_ROW: &str = "(\
42, 9223372036854775807, 12345678901234567890.1234567890, 1.5, 'txt', '', \
'bytes', '2024-03-01 10:20:30.123456', '2024-03-01 10:20:30', '2024-03-01', \
'10:20:30', 2024, b'10101010', 'a', 'x,y', \
'123e4567-e89b-12d3-a456-426614174000', '192.0.2.7', \
'2001:0db8:0000:0000:0000:0000:0000:0001', NULL)";
const WRITTEN_DECIMAL: &str = "12345678901234567890.1234567890";
const COVERED: &[(&str, &str, &str)] = &[
("n", "int(11)", "integer"),
("w", "bigint(20)", "wide_integer"),
("d", "decimal(30,10)", "exact_decimal"),
("f", "double", "floating_point"),
("s", "varchar(30)", "text"),
("em", "varchar(30)", "text"),
("b", "blob", "binary"),
("dt", "datetime(6)", "date_time"),
("ts", "timestamp", "timestamp"),
("da", "date", "date"),
("tm", "time", "time"),
("y", "year(4)", "year"),
("bi", "bit(8)", "bits"),
("e", "enum('a','b')", "single_choice"),
("st", "set('x','y')", "choice_set"),
("u", "uuid", "uuid"),
("a4", "inet4", "inet4"),
("a6", "inet6", "inet6"),
("missing", "int(11)", "absent"),
];
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_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}`"))
}
fn published_form(sandbox: &Sandbox, family: &str) -> String {
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();
rows.iter()
.find(|row| row["family"] == family)
.unwrap_or_else(|| panic!("the map publishes no family `{family}`"))["emitted"]
.as_str()
.unwrap_or_default()
.to_owned()
}
fn takes_the_form(value: &Value, form: &str) -> bool {
match form {
"number" => value.is_number(),
"text" => value.is_string(),
"absent" => value.is_null(),
"structure" => value.is_object() || value.is_array(),
"description" => value.is_object() && value["kind"].is_string(),
_ => false,
}
}
#[test]
fn fr_043_every_family_the_server_declares_is_printed_in_the_published_form() {
let Some(dsn) = writable("the printed form of every declared family") else {
return;
};
let sandbox = Sandbox::new();
let mut fixture = Fixture::new(&sandbox, &dsn);
let table = format!("typed_{}", unique_mark());
fixture.build(
&format!("CREATE TABLE {table} ({TYPED_SHAPE})"),
format!("DROP TABLE IF EXISTS {table}"),
);
fixture.fill(&format!("INSERT INTO {table} VALUES {TYPED_ROW}"));
let described = fixture.run(&["schema", "columns", "--table", &table]);
assert_eq!(
described.code, 0,
"the description must be served: {}",
described.err
);
let described_rows = described.rows();
let read = fixture.run(&["query", "run", &format!("SELECT * FROM {WRITABLE}.{table}")]);
assert_eq!(read.code, 0, "the read must be served: {}", read.err);
let rows = read.rows();
assert_eq!(rows.len(), 1, "one row was written: {}", read.out);
let row = &rows[0];
for (column, declared, family) in COVERED {
assert_eq!(
row_named(&described_rows, column)["type"],
Value::from(*declared),
"the server must declare `{column}` as `{declared}`, which is what \
makes its family `{family}` something the server said"
);
let form = published_form(&sandbox, family);
assert!(
takes_the_form(&row[*column], &form),
"`{column}` is of family `{family}`, published as `{form}`, and the \
server's own value arrived as {}",
row[*column]
);
}
assert_eq!(
row["d"],
Value::from(WRITTEN_DECIMAL),
"a large decimal must arrive with every digit it was written with"
);
assert_eq!(
row["em"],
Value::from(""),
"empty text is text the server holds and must arrive as text"
);
assert!(
row["missing"].is_null(),
"absence must be its own mark and never empty text: {}",
row["missing"]
);
assert_ne!(row["em"], row["missing"], "absence was told for empty text");
}
#[test]
fn fr_073_the_reported_origin_names_columns_the_server_really_holds() {
let Some(dsn) = writable("the physical origin of the result columns") else {
return;
};
let sandbox = Sandbox::new();
let mut fixture = Fixture::new(&sandbox, &dsn);
let parent = format!("origin_parent_{}", unique_mark());
let child = format!("origin_child_{}", unique_mark());
fixture.build(
&format!("CREATE TABLE {parent} (id INT PRIMARY KEY, label VARCHAR(20))"),
format!("DROP TABLE IF EXISTS {parent}"),
);
fixture.build(
&format!(
"CREATE TABLE {child} (id INT PRIMARY KEY, pid INT, amount INT, \
FOREIGN KEY (pid) REFERENCES {parent}(id))"
),
format!("DROP TABLE IF EXISTS {child}"),
);
let traced = fixture.run(&[
"query",
"lineage",
&format!(
"SELECT c.amount, p.label, c.amount + 1 AS bumped \
FROM {child} c JOIN {parent} p ON p.id = c.pid"
),
]);
assert_eq!(traced.code, 0, "the origin must be served: {}", traced.err);
let rows = traced.rows();
assert_eq!(
rows.len(),
3,
"three result columns were asked for: {}",
traced.out
);
let mut seen = 0usize;
for row in &rows {
let sources = row["sources"]
.as_array()
.unwrap_or_else(|| panic!("a result column resolved to nothing: {row}"))
.clone();
assert!(
!sources.is_empty(),
"every result column must resolve to a physical one: {row}"
);
for source in &sources {
let table = source["table"].as_str().unwrap_or_default();
let column = source["column"].as_str().unwrap_or_default();
assert!(
table == parent || table == child,
"`{table}` is not one of the tables this statement reads"
);
let held = fixture.run(&["schema", "columns", "--table", table]);
assert_eq!(held.code, 0, "the description of `{table}`: {}", held.err);
assert!(
held.rows().iter().any(|one| one["name"] == column),
"the origin names `{table}.{column}` and the server holds no such column"
);
seen += 1;
}
}
assert!(
seen >= 3,
"only {seen} origins were checked against the server"
);
let refused = fixture.run(&[
"query",
"lineage",
&format!("SELECT id FROM {child} JOIN {parent} ON {parent}.id = {child}.pid"),
]);
assert_eq!(
refused.code, 3,
"an ambiguous column must be refused: {}",
refused.err
);
assert_eq!(refused.code(), "lineage.ambiguous_column");
assert!(
refused.failure()["error"]["message"]
.as_str()
.is_some_and(|said| said.contains("id")),
"the refusal must name the column it is about"
);
}