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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Proving what is answered about one named object, against a real server.
//!
//! # Why this file exists
//!
//! The readings here are about a single object rather than a listing, and each
//! of them promises something a projection alone cannot show: that a definition
//! really recreates what it describes, that a column the server hides is still
//! reported, that a count says out loud whether it was counted or guessed.
//!
//! Three of them need an object shaped for the purpose, so this file builds one
//! and takes it away again. The name carries a mark no other run repeats, so two
//! runs against the same server never meet, and the removal is written in a
//! guard so a failed assertion still leaves the server as it was found.

// 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::Value;
use support::server::{destination_or_skip, on_server, unique_mark};
use support::{Outcome, Sandbox};

/// The database every fixture of this file lives in.
const FIXTURE_DATABASE: &str = "shop";

/// The character rules the fixture table itself is written under.
const TABLE_COLLATION: &str = "utf8mb4_general_ci";

/// The character rules one column of the fixture overrides them with.
const COLUMN_COLLATION: &str = "utf8mb4_bin";

/// A table of this run alone, removed when the proof that made it ends.
struct Fixture<'a> {
    sandbox: &'a Sandbox,
    dsn: String,
    name: String,
}

impl<'a> Fixture<'a> {
    /// Builds the table, with a hidden column and a column whose character
    /// rules differ from the table's own.
    ///
    /// # Panics
    ///
    /// Panics when the server refuses to build it, which is a failure of the
    /// proof rather than a reason to carry on without a subject.
    fn build(sandbox: &'a Sandbox, dsn: &str) -> Self {
        let made = Self {
            sandbox,
            dsn: dsn.to_owned(),
            name: format!("structure_probe_{}", unique_mark()),
        };
        let statement = format!(
            "CREATE TABLE {name} (\
               id int NOT NULL AUTO_INCREMENT, \
               tag varchar(20) COLLATE {COLUMN_COLLATION} NOT NULL, \
               hidden_col int INVISIBLE, \
               PRIMARY KEY (id)\
             ) CHARACTER SET utf8mb4 COLLATE {TABLE_COLLATION}",
            name = made.name
        );
        let built = made.statement(&statement);
        assert_eq!(built.code, 0, "the fixture must be built: {}", built.err);
        made
    }

    /// Runs one statement that changes the server.
    fn statement(&self, written: &str) -> Outcome {
        on_server(self.sandbox, &self.dsn, &["--yes", "query", "run", written])
    }

    /// Runs one reading against this table.
    fn read(&self, command: &[&str]) -> Outcome {
        let mut whole: Vec<&str> = command.to_vec();
        whole.extend_from_slice(&["--database", FIXTURE_DATABASE]);
        on_server(self.sandbox, &self.dsn, &whole)
    }
}

impl Drop for Fixture<'_> {
    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.
        let removed = self.statement(&format!("DROP TABLE IF EXISTS {}", self.name));
        support::server::confirm_removed(&removed, &format!("the table {}", self.name));
    }
}

/// FR-118. The definition the server emits recreates the object it describes:
/// the table is read, taken away, built again from that text alone, and
/// describes itself identically afterwards.
#[test]
fn the_definition_the_server_emits_recreates_the_object_it_describes() {
    let Some(dsn) = destination_or_skip("the textual definition of an object") else {
        return;
    };
    let sandbox = Sandbox::new();
    let fixture = Fixture::build(&sandbox, &dsn);

    let before = fixture.read(&["schema", "columns", "--table", &fixture.name]);
    assert_eq!(before.code, 0, "the description: {}", before.err);

    let definition = fixture.read(&["schema", "ddl", &fixture.name]);
    assert_eq!(definition.code, 0, "the definition: {}", definition.err);
    let written = definition.answer()["data"]["definition"]
        .as_str()
        .unwrap_or_else(|| panic!("no definition was returned: {}", definition.out))
        .to_owned();
    assert!(
        written.to_uppercase().contains("CREATE TABLE"),
        "the definition must be the statement that builds it: {written}"
    );

    let removed = fixture.statement(&format!("DROP TABLE {}", fixture.name));
    assert_eq!(
        removed.code, 0,
        "the table must be removable: {}",
        removed.err
    );
    let rebuilt = fixture.statement(&written);
    assert_eq!(
        rebuilt.code, 0,
        "the definition the server emitted was refused by the server: {}",
        rebuilt.err
    );

    let after = fixture.read(&["schema", "columns", "--table", &fixture.name]);
    assert_eq!(
        after.code, 0,
        "the description of the rebuilt table: {}",
        after.err
    );
    assert_eq!(
        before.rows(),
        after.rows(),
        "the object was rebuilt from its own definition and came back different"
    );
}

/// FR-119. A sample never returns more rows than the caller asked for, so the
/// number in the request is a ceiling and not a suggestion.
#[test]
fn a_sample_never_returns_more_rows_than_were_asked_for() {
    let Some(dsn) = destination_or_skip("the sample of a table") else {
        return;
    };
    let sandbox = Sandbox::new();

    // A table with more rows in it than the smallest sample asks for, or the
    // ceiling below would never be reached and would prove nothing.
    let counted = on_server(
        &sandbox,
        &dsn,
        &[
            "schema",
            "count",
            "--database",
            FIXTURE_DATABASE,
            "--table",
            "orders",
        ],
    );
    assert_eq!(counted.code, 0, "the count: {}", counted.err);
    let held = counted.answer()["data"]["rows"]
        .as_u64()
        .unwrap_or_else(|| panic!("the count carries no number: {}", counted.out));
    assert!(
        held >= 2,
        "this table holds {held} rows and cannot fill a sample"
    );

    for asked in ["1", "2"] {
        let sampled = on_server(
            &sandbox,
            &dsn,
            &[
                "query",
                "sample",
                "--database",
                FIXTURE_DATABASE,
                "--table",
                "orders",
                "--limit",
                asked,
            ],
        );
        assert_eq!(sampled.code, 0, "the sample of {asked}: {}", sampled.err);

        let answer = sampled.answer();
        let returned = answer["data"]["rows"]
            .as_array()
            .unwrap_or_else(|| panic!("the sample carries no rows: {answer}"))
            .len();
        let ceiling: usize = asked.parse().expect("a written number");
        assert!(
            returned <= ceiling,
            "a sample of {ceiling} returned {returned} rows"
        );
        assert_eq!(
            answer["data"]["row_count"], returned,
            "the declared count and the rows themselves disagree: {answer}"
        );
    }
}

/// FR-120. The count that reads the rows declares itself exact and never
/// approximate, which is the whole reason for paying for it instead of taking
/// the estimate.
#[test]
fn the_count_that_reads_the_rows_declares_itself_exact() {
    let Some(dsn) = destination_or_skip("the exact count") else {
        return;
    };
    let sandbox = Sandbox::new();
    let counted = on_server(
        &sandbox,
        &dsn,
        &[
            "schema",
            "count",
            "--database",
            FIXTURE_DATABASE,
            "--table",
            "orders",
        ],
    );
    assert_eq!(counted.code, 0, "the count must be served: {}", counted.err);

    let answer = counted.answer();
    assert_eq!(
        answer["data"]["exact"],
        Value::Bool(true),
        "a count that read the rows must say so: {answer}"
    );
    assert_eq!(
        answer["data"]["estimated"],
        Value::Bool(false),
        "an exact count must never also be published as an estimate: {answer}"
    );
    assert!(
        answer["data"]["rows"].is_number(),
        "the count itself must be a number: {answer}"
    );
}

/// FR-121. The character rules are declared at all three levels, and a column
/// that overrides its table really reads back as different from it — so a
/// caller comparing text knows which rule applies where.
#[test]
fn a_column_that_overrides_the_character_rules_reads_back_as_different() {
    let Some(dsn) = destination_or_skip("the character rules of an object") else {
        return;
    };
    let sandbox = Sandbox::new();
    let fixture = Fixture::build(&sandbox, &dsn);

    let databases = on_server(&sandbox, &dsn, &["schema", "databases"]);
    assert_eq!(databases.code, 0, "the databases: {}", databases.err);
    let database = databases
        .rows()
        .into_iter()
        .find(|row| row["name"] == FIXTURE_DATABASE)
        .unwrap_or_else(|| panic!("the fixture's database is missing: {}", databases.out));
    assert!(
        database["character_set"].is_string() && database["collation"].is_string(),
        "a database must declare its character rules: {database}"
    );

    let tables = fixture.read(&["schema", "tables", "--detail", "full"]);
    assert_eq!(tables.code, 0, "the tables: {}", tables.err);
    let table = tables
        .rows()
        .into_iter()
        .find(|row| row["name"] == fixture.name.as_str())
        .unwrap_or_else(|| panic!("the fixture is missing from the listing: {}", tables.out));
    assert_eq!(
        table["collation"], TABLE_COLLATION,
        "the table's own rules were not read: {table}"
    );

    let columns = fixture.read(&["schema", "columns", "--table", &fixture.name]);
    assert_eq!(columns.code, 0, "the columns: {}", columns.err);
    let overriding = columns
        .rows()
        .into_iter()
        .find(|row| row["name"] == "tag")
        .unwrap_or_else(|| panic!("the overriding column is missing: {}", columns.out));
    assert_eq!(
        overriding["collation"], COLUMN_COLLATION,
        "the column's own rules were not read: {overriding}"
    );
    assert_ne!(
        overriding["collation"], table["collation"],
        "a column that overrides its table came back agreeing with it"
    );
}

/// FR-123. A column the server hides is still listed, and is marked as hidden;
/// reading every column of the table returns the others and never that one, so
/// the listing tells a caller something the reading cannot.
#[test]
fn a_hidden_column_is_listed_and_is_never_returned_by_reading_them_all() {
    let Some(dsn) = destination_or_skip("the marks a column carries") else {
        return;
    };
    let sandbox = Sandbox::new();
    let fixture = Fixture::build(&sandbox, &dsn);

    let columns = fixture.read(&["schema", "columns", "--table", &fixture.name]);
    assert_eq!(columns.code, 0, "the columns: {}", columns.err);
    let rows = columns.rows();

    let hidden = rows
        .iter()
        .find(|row| row["name"] == "hidden_col")
        .unwrap_or_else(|| panic!("the hidden column was not listed at all: {rows:?}"));
    assert_eq!(
        hidden["invisible"], 1,
        "the hidden column is not marked: {hidden}"
    );

    // The column the server fills by itself is marked apart from the hidden
    // one, because an insertion has to omit both for different reasons.
    let automatic = rows
        .iter()
        .find(|row| row["name"] == "id")
        .unwrap_or_else(|| panic!("the automatic column is missing: {rows:?}"));
    assert_eq!(
        automatic["server_filled"], 1,
        "a column the server fills must say so: {automatic}"
    );
    assert_eq!(
        automatic["invisible"], 0,
        "being filled by the server is not being hidden: {automatic}"
    );

    let read = on_server(
        &sandbox,
        &dsn,
        &[
            "query",
            "run",
            &format!("SELECT * FROM {}.{}", FIXTURE_DATABASE, fixture.name),
        ],
    );
    assert_eq!(read.code, 0, "reading every column: {}", read.err);
    let returned: Vec<String> = read.answer()["data"]["columns"]
        .as_array()
        .unwrap_or_else(|| panic!("the reading names no columns: {}", read.out))
        .iter()
        .filter_map(|name| name.as_str().map(ToOwned::to_owned))
        .collect();

    assert!(
        returned.iter().any(|name| name == "tag"),
        "the ordinary columns must still arrive: {returned:?}"
    );
    assert!(
        !returned.iter().any(|name| name == "hidden_col"),
        "the hidden column was returned by reading them all: {returned:?}"
    );
}

/// FR-141. The restriction a table imposes on its values comes back with the
/// condition written out, and a table imposing none answers an empty list at
/// exit zero rather than a failure.
///
/// # Why the condition itself is asserted
///
/// A listing naming the restriction and withholding its condition tells a
/// caller that some values are refused without telling them which, which is
/// the half of the answer nobody can write an insertion from. So the text is
/// read out of the row and matched against the column it guards.
///
/// # Why this one builds nothing
///
/// Its neighbours above build a table because what they assert cannot be seen
/// on a table somebody else made. This one can, and building would put two more
/// short-lived tables into a database whose listings other proofs are counting
/// at the same moment.
#[test]
fn the_restriction_a_table_imposes_comes_back_with_its_condition() {
    let Some(dsn) = destination_or_skip("the value restrictions of a table") else {
        return;
    };
    let sandbox = Sandbox::new();

    let listed = on_server(
        &sandbox,
        &dsn,
        &[
            "schema",
            "checks",
            "--database",
            FIXTURE_DATABASE,
            "--table",
            "strict_rows",
        ],
    );
    assert_eq!(
        listed.code, 0,
        "the restrictions must be served: {}",
        listed.err
    );
    let rows = listed.rows();
    assert!(
        !rows.is_empty(),
        "this table declares a restriction and none came back"
    );
    let condition = rows[0]["condition"]
        .as_str()
        .unwrap_or_else(|| panic!("the restriction carries no condition: {}", listed.out));
    assert!(
        condition.contains("amount"),
        "the condition must name what it guards: {condition}"
    );
    assert!(
        rows[0]["level"].is_string(),
        "the level says where the restriction was written: {rows:?}"
    );

    let none = on_server(
        &sandbox,
        &dsn,
        &[
            "schema",
            "checks",
            "--database",
            FIXTURE_DATABASE,
            "--table",
            "orders",
        ],
    );
    assert_eq!(
        none.code, 0,
        "no restriction is not a failure: {}",
        none.err
    );
    assert!(
        none.rows().is_empty(),
        "a table imposing nothing answered with something: {:?}",
        none.rows()
    );
}