mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Proving the compact map and the read path against a real server.
//!
//! # Why this file exists
//!
//! Both requirements below were carried by readings that never left this
//! process. The compact map was measured over an answer this suite assembled,
//! so nothing said the shape being compressed was a shape a server reported;
//! and the read path was measured over columns built by hand, so nothing said a
//! server had ever answered one of them.
//!
//! That is the exact shape of the defect this round came from: the product
//! agreed with the local artefact and disagreed with the server, and the proof
//! agreed with the artefact too, so nobody saw it. Every reading here therefore
//! builds real objects on the declared destination, asks the server what it
//! holds, and compares the product's answer against that.
//!
//! Whatever a proof builds it takes away again in a guard, so a failed
//! assertion still leaves the server as it was found.

// The support module serves every proof file in this directory, so the parts
// this one does not need are used by its neighbours.
#[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};

/// The database these proofs are allowed to build in.
///
/// Never the one the destination names by itself: that database is shared with
/// every other proof of this suite, and a file that creates and drops tables
/// belongs somewhere set aside for exactly that.
const WRITABLE: &str = "bulk";

/// The comment one fixture column carries, so its absence from the map is
/// something that was really there to leave out.
const WRITTEN_COMMENT: &str = "uma nota que o mapa nao deve carregar";

/// How much smaller than the full description the map has to be.
const COMPRESSION: usize = 10;

/// A destination this file may build in, or nothing when none was declared.
fn writable(proof: &str) -> Option<String> {
    destination_or_skip(proof).map(|dsn| aimed_at(&dsn, WRITABLE))
}

/// Objects this run alone built, taken away when the proof that made them ends.
struct Fixture<'a> {
    /// Where the invocations are driven from.
    sandbox: &'a Sandbox,
    /// The destination the objects live on.
    dsn: String,
    /// Every statement that has to run to leave the server as it was found.
    undo: Vec<String>,
}

impl<'a> Fixture<'a> {
    /// An empty holding, which owns nothing until something is built into it.
    fn new(sandbox: &'a Sandbox, dsn: &str) -> Self {
        Self {
            sandbox,
            dsn: dsn.to_owned(),
            undo: Vec::new(),
        }
    }

    /// Runs one invocation against the destination these objects live on.
    fn run(&self, args: &[&str]) -> Outcome {
        on_server(self.sandbox, &self.dsn, args)
    }

    /// Builds one object and records how to take it away.
    ///
    /// # Panics
    ///
    /// Panics when the server refuses to build it, which is the proof's own
    /// ground giving way rather than a reason to carry on without a subject.
    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);
    }

    /// Writes rows so they outlive the invocation that wrote them.
    ///
    /// An ordinary change does not survive its own session here, on purpose, so
    /// rows are written the one way that keeps them and a proof that read an
    /// empty table and called it a wrong answer is not possible.
    ///
    /// # Panics
    ///
    /// Panics when the rows cannot be written.
    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) {
        // Taken away in the reverse of the order they were built, so an object
        // leaning on an earlier one goes first. 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 undo in self.undo.iter().rev() {
            let removed = self.run(&["--yes", "query", "run", undo]);
            support::server::confirm_removed(&removed, undo);
        }
    }
}

/// The row of a listing whose named field carries the value asked for.
///
/// # Panics
///
/// Panics when no row carries it, which means the reading under test never
/// reached the object the proof built.
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:?}"))
}

/// Every text of an array field of one row, as plain strings.
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()
}

/// How many plain columns each fixture table carries beyond its keys.
///
/// Wide on purpose. The map spends one line on a table however many columns it
/// has, and the full description spends a line on every column, so the ratio the
/// requirement states is only worth measuring on a table with columns to leave
/// out.
const PLAIN_COLUMNS: usize = 20;

/// The plain columns of a fixture table, declared.
fn plain_columns() -> String {
    (0..PLAIN_COLUMNS)
        .map(|at| format!("plain_{at:02} VARCHAR(40)"))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Builds a parent and a child linked to it, and hands back both names.
///
/// The parent carries a written comment on one of its columns, so the omission
/// the map claims is the omission of something that was really there.
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)
}

/// The link the SERVER holds for this child, written the way a map states one.
///
/// # Panics
///
/// Panics when the server holds no reference for it, which would leave the map
/// with nothing to be checked against.
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()
    )
}

/// How many bytes the full description of every table the map names costs.
///
/// The whole document is measured on both sides, because what a caller pays for
/// is the document rather than the payload inside it.
///
/// A table the map named and the server no longer holds is left out rather than
/// failed on: this database is shared with the neighbouring proofs of this
/// suite, and one of them tidying up between the two readings is ordinary. That
/// is safe in this direction only, and it is this direction: leaving a table out
/// lowers the full description and never the map, so it can only make the
/// comparison below harder to pass. The tables this proof owns are named by the
/// caller and are never allowed to be the ones that went missing.
///
/// # Panics
///
/// Panics when a table this proof owns cannot be described.
fn full_description_bytes(fixture: &Fixture, rows: &[Value], owned: &[&str]) -> usize {
    let mut whole = 0;
    for row in rows {
        // The subject of a map row is under `name`, as it is in every listing.
        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
}

/// FR-020. The compact map of a real database carries the shape the SERVER
/// reports for it, leaves out the full type and the comment, and is at least
/// ten times smaller than the full description of the same tables.
///
/// Every half is measured against the server rather than against an answer this
/// file assembled. The key marks the map prints are compared with the marks the
/// catalogue gives those same columns, and the link it prints is compared with
/// the reference the server itself holds, so a map agreeing with a local
/// artefact and disagreeing with the destination fails here.
#[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();

    // What the server says about the same two tables, read on its own.
    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:?}"
    );

    // The omissions the requirement states, measured against things that are
    // really there to leave out: a declared width and a written comment.
    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"
    );
}

/// FR-022. A read the server really answered arrives with the column names the
/// server labelled and the values it holds, and two statements in one call are
/// refused without the destination being touched.
///
/// The rows are written first and read back in an invocation of its own, so
/// what is asserted is a result packet a server sent rather than a set of
/// columns this file assembled. The refusal is followed by a second reading of
/// the same table: a refusal reported after the statements had already run
/// would give the same exit number and only the table tells the two apart.
#[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"
    );
}