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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! What the contract of one command says, and whether the product keeps it.
//!
//! Split from `published_contract.rs` when that file went past the ceiling this
//! project holds every file to. The cut follows the subject: the neighbouring
//! file asks whether the *product's* published surface matches its documents,
//! and this asks whether the contract of a *command* matches what that command
//! really accepts, really answers and really refuses with.
//!
//! # Why most of this runs in process
//!
//! The first writing of these proofs invoked the binary once per command and
//! once per argument: a hundred and sixty-three processes to read a contract
//! that is local, deterministic and needs no server at all. Measured against the
//! real destination, that load was enough to starve the proofs in other files
//! that hold a connection open — they reported that their own statement never
//! appeared, which was true, and was about this file rather than about the
//! product.
//!
//! So the readings that can be made from the library are made from the library,
//! and they are made against the same functions the binary calls. The one proof
//! that still spawns is the one that must: a failure envelope is written by a
//! process on its way out, and nothing short of a process writes one.

// 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 clap::{CommandFactory as _, Parser as _};
use mariadb_cli::cli::meta::{MetaCommand, SchemaArgs};
use mariadb_cli::cli::Cli;
use mariadb_cli::commands::{contract, meta, SERVED_LEAVES};
use support::Sandbox;

/// The contract of one command, built the way the binary builds it.
///
/// # Panics
///
/// Panics when the product refuses to describe a command it publishes, which is
/// the defect worth failing over.
fn contract_of(leaf: &str) -> serde_json::Value {
    // Any parsed invocation will do: the contract of a command does not depend
    // on the invocation that asked for it, which is itself part of the promise.
    let cli = Cli::try_parse_from(["mariadb-cli", "meta", "version"])
        .expect("the simplest invocation of all must parse");
    let asked = MetaCommand::Schema(SchemaArgs {
        command: Some(leaf.to_owned()),
        types: false,
    });
    let envelope = meta::execute(&asked, &cli)
        .unwrap_or_else(|failure| panic!("`{leaf}` has no contract: {}", failure.code()));
    envelope.data
}

/// FR-047 and FR-053. The contract names every field a failure carries.
///
/// The proof in the neighbouring file reads a successful answer and compares the
/// keys of its top level. That leaves two whole surfaces unread: what travels
/// inside `data`, and what a failure looks like. The second is the one that had
/// a field nobody had declared — `causes` — carried on every refusal for as long
/// as the product had refusals, named in no requirement and in no contract.
///
/// So the failures are produced rather than described. Three of them, chosen to
/// carry different optional fields: one with a cause from the argument parser,
/// one with a hint and a detail, and one that had to resolve a destination
/// first. A field that only appears on one of the three would be missed by
/// reading only the others.
#[test]
fn the_published_contract_names_every_field_a_failure_carries() {
    let sandbox = Sandbox::new();

    let published = contract::failure_shape()["shape"]
        .as_object()
        .expect("the contract describes the shape of a failure")
        .keys()
        .cloned()
        .collect::<std::collections::BTreeSet<String>>();
    assert!(
        !published.is_empty(),
        "a contract that describes no failure field cannot catch an undeclared one"
    );

    let refusals: [&[&str]; 3] = [
        &["query", "run", "--zzz-not-a-flag"],
        &["meta", "schema", "--command", "no-such-command"],
        &[
            "--dsn",
            "this is not a destination",
            "query",
            "run",
            "SELECT 1",
        ],
    ];

    for args in refusals {
        let refused = sandbox.run(args);
        assert_ne!(
            refused.code, 0,
            "this invocation must be refused, or it proves nothing: {args:?}"
        );
        let body = refused.failure();
        let carried = body["error"]
            .as_object()
            .unwrap_or_else(|| panic!("a failure is an object: {body}"))
            .keys()
            .cloned()
            .collect::<std::collections::BTreeSet<String>>();

        let unpublished: Vec<&String> = carried.difference(&published).collect();
        assert!(
            unpublished.is_empty(),
            "the failure of {args:?} carries fields the contract never names: {unpublished:?}"
        );
    }
}

/// FR-053. Every published command says what it can do to the world.
///
/// The promise is inputs, outputs, failures and effects, and the effect is the
/// half no parser can answer: whether a command changes anything is decided by
/// what it sends. So it is written by hand, and this is what stops the hand
/// written list from going quiet — the names come from the build's own list of
/// served leaves, so a command added there and forgotten in the effects answers
/// `unpublished` and fails here rather than passing unnoticed.
///
/// Two lists compared, and not one read twice: that is the whole content of this
/// proof, and it is why reading both from the library costs it nothing.
#[test]
fn every_published_command_declares_what_it_can_change() {
    let published = ["local", "reads", "may_change"];
    let missing: Vec<String> = SERVED_LEAVES
        .iter()
        .map(|leaf| (*leaf, contract::effect_of(leaf)))
        .filter(|(_, effect)| !published.contains(effect))
        .map(|(leaf, effect)| format!("{leaf} => {effect}"))
        .collect();

    assert!(
        missing.is_empty(),
        "these commands publish no effect from the closed set {published:?}: {missing:?}"
    );
}

/// FR-053. Every input the contract names is one the parser really accepts.
///
/// The requirement says it in those words, and until now nothing held the
/// product to it, because the contract named no input at all. Naming them from
/// the parser's own tree makes them right by construction; feeding them back to
/// that parser makes the construction observable, and would catch the day the
/// contract starts being written from somewhere else.
///
/// The parser is asked directly rather than through a process. What is being
/// checked is whether an argument is known, and that is answered before a single
/// byte would have left for a server.
#[test]
fn every_input_the_contract_names_is_accepted_by_the_parser() {
    let root = Cli::command();
    let mut checked = 0_usize;
    let mut rejected: Vec<String> = Vec::new();

    for leaf in SERVED_LEAVES {
        let inputs = contract::inputs_of(&root, leaf);
        let inputs = inputs
            .as_array()
            .unwrap_or_else(|| panic!("`{leaf}` publishes no list of inputs"));

        for input in inputs {
            // A positional is named, not written, so there is no spelling of it
            // the parser could reject as unknown.
            if input["kind"] == "positional" {
                continue;
            }
            let name = input["name"].as_str().expect("an input has a name");
            let written = format!("--{name}");
            let mut argv: Vec<String> = vec!["mariadb-cli".to_owned()];
            argv.extend(leaf.split(' ').map(ToOwned::to_owned));
            argv.push(written.clone());

            checked += 1;
            // The parse is expected to fail for want of a value or of a
            // companion argument. The one refusal that must never happen is the
            // parser saying it has never heard of the name.
            if let Err(refusal) = Cli::command().try_get_matches_from(&argv) {
                if refusal.kind() == clap::error::ErrorKind::UnknownArgument {
                    rejected.push(format!("{leaf} {written}"));
                }
            }
        }
    }

    assert!(
        checked > 40,
        "the inputs must be read, or this proof checks nothing"
    );
    assert!(
        rejected.is_empty(),
        "the contract names inputs the parser does not accept: {rejected:?}"
    );
}

/// FR-053. The contract of every command carries all four things it promises.
///
/// Written as one reading of every served leaf, because the promise is a set and
/// a set is kept whole or not at all. A contract carrying three of the four
/// would satisfy each of the proofs above and still break the sentence the
/// requirement wrote.
#[test]
fn the_contract_of_every_command_carries_inputs_effect_failures_and_envelope() {
    let promised = ["inputs", "effect", "data", "failures", "envelope"];
    let mut short: Vec<String> = Vec::new();

    for leaf in SERVED_LEAVES {
        let data = contract_of(leaf);
        let absent: Vec<&str> = promised
            .iter()
            .copied()
            .filter(|field| data.get(*field).is_none())
            .collect();
        if !absent.is_empty() {
            short.push(format!("{leaf} lacks {absent:?}"));
        }
    }

    assert!(
        short.is_empty(),
        "the contract does not carry everything FR-053 promises: {short:?}"
    );
}

/// FR-053. A described payload belongs to a command this build actually serves.
///
/// The table of payload shapes is written by hand, so the first way it can go
/// wrong is by describing something that is not there: a command renamed or
/// withdrawn leaves its description behind, and the description keeps being
/// published for a name nobody can invoke.
#[test]
fn no_payload_is_described_for_a_command_this_build_does_not_serve() {
    let stray: Vec<&str> = contract::commands_with_published_data()
        .into_iter()
        .chain(contract::commands_whose_data_varies())
        .filter(|leaf| !SERVED_LEAVES.contains(leaf))
        .collect();

    assert!(
        stray.is_empty(),
        "a payload is described for commands that are not served: {stray:?}"
    );
}

/// Fields whose description does not open with a type, and why not.
///
/// The type check reads the first word of a description, so a field described
/// in prose is a field nothing checks. That is sometimes right and it is never
/// free, which is why the exceptions are named here rather than counted.
///
/// All three are the same field for the same reason: a setting's value has the
/// type of that setting, so one word would have to stand for text, number and
/// switch at once. Writing "string" there would be checkable and wrong, which
/// is the worst pair of properties a contract can have.
const UNTYPED: [(&str, &str, &str); 3] = [
    (
        "config get",
        "value",
        "the type is the setting's own, so no single word covers it",
    ),
    (
        "config set",
        "value",
        "the type is the setting's own, so no single word covers it",
    ),
    (
        "config unset",
        "value",
        "the type is the setting's own, so no single word covers it",
    ),
];

/// FR-053. Every described field declares a type, or is named as not doing so.
///
/// Written after measuring rather than before: five of eighty-six descriptions
/// opened with prose, and two of those were only phrased that way — "array of
/// three numbers" and "object describing the transaction" both name a type and
/// neither was checked, because the check reads a word and a comma. Rewording
/// them cost nothing and bought two more checked fields.
///
/// The three that remain are genuine. Naming them stops the number from growing
/// back quietly: a field added in prose is a field outside the type check, and
/// the whole reason that check exists is that a wrong type survived review.
#[test]
fn every_described_field_declares_its_type_or_is_named_as_not_declaring_one() {
    let mut prose: Vec<String> = Vec::new();

    for leaf in contract::commands_with_published_data() {
        let shape = contract::data_shape_of(leaf);
        let fields = shape.as_object().expect("a described payload is an object");
        for (field, about) in fields {
            let described = about.as_str().unwrap_or_default();
            if support::described::declared_type(described).is_some() {
                continue;
            }
            if UNTYPED
                .iter()
                .any(|(command, name, _)| *command == leaf && name == field)
            {
                continue;
            }
            prose.push(format!("{leaf}.{field}"));
        }
    }

    assert!(
        prose.is_empty(),
        "these are described in prose, so no proof checks their type, and none \
         of them is named as an exception: {prose:?}"
    );

    let stray: Vec<String> = UNTYPED
        .iter()
        .filter(|(leaf, field, _)| {
            contract::data_shape_of(leaf)
                .get(field)
                .and_then(serde_json::Value::as_str)
                .is_none_or(|about| support::described::declared_type(about).is_some())
        })
        .map(|(leaf, field, _)| format!("{leaf}.{field}"))
        .collect();

    assert!(
        stray.is_empty(),
        "these are named as untyped and either declare a type now or are not \
         described at all; the exception has to go when its reason does: {stray:?}"
    );
}

/// FR-053. A declared absence is about a field that is actually described.
///
/// This table is the one place in the payload contract that lets a proof accept
/// something missing, which makes it the one place worth guarding against being
/// used to make a failure go away. An entry naming a command that describes no
/// payload, or a field that command does not describe, excuses nothing and
/// reads as though it does.
#[test]
fn every_declared_absence_names_a_field_that_is_described() {
    let described = contract::commands_with_published_data();
    let mut stray: Vec<String> = Vec::new();

    for (leaf, field) in contract::conditional_fields() {
        if !described.contains(&leaf) {
            stray.push(format!("{leaf} has no published payload for `{field}`"));
            continue;
        }
        let shape = contract::data_shape_of(leaf);
        if shape.get(field).is_none() {
            stray.push(format!("{leaf} describes no field named `{field}`"));
        }
    }

    assert!(
        stray.is_empty(),
        "these declared absences excuse nothing: {stray:?}"
    );
}

/// FR-053. No command both names its payload and says the payload varies.
///
/// The two answers contradict each other: one tells a caller the field set is
/// fixed and safe to validate against, the other tells them it is not. Which
/// one a caller would get depends on the order the lookup happens to try, which
/// is exactly the kind of decision no contract should be making by accident.
#[test]
fn no_command_both_publishes_a_payload_and_declares_it_variable() {
    let fixed = contract::commands_with_published_data();
    let both: Vec<&str> = contract::commands_whose_data_varies()
        .into_iter()
        .filter(|leaf| fixed.contains(leaf))
        .collect();

    assert!(
        both.is_empty(),
        "these commands claim a fixed payload and a variable one at once: {both:?}"
    );
}

/// FR-053. A command whose payload varies says so, and says why.
///
/// Stating only that the shape is absent would read as work not yet done. The
/// reason is what lets a caller tell an unfinished description from a command
/// whose answer genuinely depends on what was asked, and act differently.
#[test]
fn a_command_with_a_variable_payload_publishes_the_reason() {
    let mut silent: Vec<String> = Vec::new();

    for leaf in contract::commands_whose_data_varies() {
        let data = contract_of(leaf);
        if data["data"]["shape_varies_by_input"].as_str().is_none() {
            silent.push(leaf.to_owned());
        }
    }

    assert!(
        silent.is_empty(),
        "these commands declare a variable payload without saying why: {silent:?}"
    );
}

/// FR-053. A command without a described payload says so where it is read.
///
/// The limit used to be stated once, on the envelope, which told a reader that
/// no command described its payload. Now that some do, the same sentence would
/// be false for them and misleading for the rest. So the statement moved to the
/// command, and this refuses the silence that would otherwise take its place: a
/// command that neither names its fields nor states the limit would be read as
/// having an empty payload.
#[test]
fn a_command_without_a_described_payload_states_that_limit_itself() {
    let described = contract::commands_with_published_data();
    let variable = contract::commands_whose_data_varies();
    let mut silent: Vec<String> = Vec::new();

    for leaf in SERVED_LEAVES {
        if described.contains(&leaf) || variable.contains(&leaf) {
            continue;
        }
        let data = contract_of(leaf);
        if data["data"]["declared_limit"].as_str().is_none() {
            silent.push(leaf.to_owned());
        }
    }

    assert!(
        silent.is_empty(),
        "these commands describe no payload and state no limit either: {silent:?}"
    );
}

/// The setting written and cleared around the reading of it.
const SETTING: &str = "conn.default";

/// A credential that only ever travels on the standard input.
const SECRET: &str = "a-secret-that-never-travels\n";

/// One invocation of one command, and the input it is handed, if any.
///
/// Ordered on purpose, and the order is the whole reason this reads as a
/// sequence rather than a set. `set` gives `get` something to read and `unset`
/// takes it away before the profile commands write that same key for their own
/// reasons; the profiles are added before they are listed, shown, chosen and
/// removed; and the saved statement exists only between the save and the
/// removal that follows it.
///
/// A command appears more than once when a flag of its own changes what it
/// answers with. One invocation per command was the hole a review walked
/// through: `meta commands` was described as fixed, `--with-globals` added a
/// field, and the proof ran it the one way that agreed with the table.
const INVOCATIONS: [(&str, &[&str], Option<&str>); 21] = [
    ("meta version", &["meta", "version"], None),
    ("meta commands", &["meta", "commands"], None),
    (
        "meta commands",
        &["meta", "commands", "--with-globals"],
        None,
    ),
    ("meta completions", &["meta", "completions", "bash"], None),
    ("meta manual", &["meta", "manual"], None),
    ("config path", &["config", "path"], None),
    ("config list", &["config", "list"], None),
    ("config doctor", &["config", "doctor"], None),
    ("config set", &["config", "set", SETTING, "alfa"], None),
    ("config get", &["config", "get", SETTING], None),
    ("config unset", &["config", "unset", SETTING], None),
    (
        "conn add",
        &[
            "conn",
            "add",
            "alfa",
            "--host",
            "127.0.0.1",
            "--port",
            "3306",
            "--user",
            "quem",
            "--password-stdin",
        ],
        Some(SECRET),
    ),
    ("conn list", &["conn", "list"], None),
    ("conn show", &["conn", "show", "alfa"], None),
    ("conn default", &["conn", "default", "alfa"], None),
    (
        "conn edit",
        &["conn", "edit", "alfa", "--port", "3307"],
        None,
    ),
    ("conn remove", &["conn", "remove", "alfa"], None),
    (
        "query lineage",
        &["query", "lineage", "SELECT 1 AS um"],
        None,
    ),
    (
        "query named save",
        &["query", "named", "save", "guardada", "SELECT 1"],
        None,
    ),
    ("query named list", &["query", "named", "list"], None),
    (
        "query named remove",
        &["query", "named", "remove", "guardada"],
        None,
    ),
];

/// FR-053. Every described payload matches the answer the command really gives.
///
/// This is the proof that makes the table safe to publish. A hand-written
/// description of something built with `json!` somewhere else is a second copy
/// of a decision, and a second copy parts company with the first one quietly.
/// So the command is run and what comes back is held to what was published, by
/// name and by type.
#[test]
fn every_described_payload_matches_the_answer_the_command_gives() {
    let sandbox = Sandbox::new();
    let invocations = INVOCATIONS;

    let mut wrong: Vec<String> = Vec::new();

    for (leaf, argv, input) in invocations {
        let outcome = match input {
            Some(text) => sandbox.run_with_input(argv, text),
            None => sandbox.run(argv),
        };
        assert_eq!(
            outcome.code, 0,
            "`{leaf}` must answer before its payload can be compared: {}",
            outcome.err
        );

        let emitted = outcome.answer();
        let mut real: Vec<String> = emitted["data"]
            .as_object()
            .unwrap_or_else(|| panic!("`{leaf}` must answer with a payload object"))
            .keys()
            .cloned()
            .collect();
        real.sort();

        let mut described: Vec<String> = contract_of(leaf)["data"]
            .as_object()
            .unwrap_or_else(|| panic!("`{leaf}` must describe its payload"))
            .keys()
            .cloned()
            .collect();
        described.sort();

        // One reading for all three proofs of this contract, in
        // `support::described`: names in both directions with declared absences
        // allowed, then types. Two of them once carried different rules and the
        // difference only surfaced when a conditional field reached the
        // stricter one and failed for being right.
        wrong.extend(support::described::disagreements(
            leaf,
            &contract::data_shape_of(leaf),
            &emitted["data"],
        ));
    }

    assert!(
        wrong.is_empty(),
        "the published payload and the real one differ: {wrong:?}"
    );

    // Without this the proof would be as strong as whoever last remembered to
    // add a line above. A command described in the table and never invoked here
    // is described by nobody, and the comparison it was supposed to survive
    // never happens — which is the same silence this file exists to refuse.
    let mut invoked: Vec<&str> = invocations.iter().map(|(leaf, _, _)| *leaf).collect();
    invoked.sort_unstable();
    invoked.dedup();
    // Narrowed to the commands that reach nowhere, because those are the ones
    // this file can run. The rest are held by `payload_shape_server.rs`, which
    // needs a destination; the two lists together have to cover the table, and
    // each file refuses the half it is responsible for.
    let mut described: Vec<&str> = contract::commands_with_published_data()
        .into_iter()
        .filter(|leaf| contract::effect_of(leaf) == "local")
        .collect();
    described.sort_unstable();

    assert_eq!(
        invoked, described,
        "every command with a published payload and no destination must be run \
         here, and only those"
    );
}

/// FR-053. The contract published by the process is the one built in process.
///
/// The three proofs above read the library directly, which is what keeps them
/// cheap. That trade is only sound while the binary answers what the library
/// builds, so the two are compared here once, on one command, through a real
/// invocation. A drift between them would make every cheap reading meaningless,
/// and this is the one proof that would notice.
#[test]
fn the_contract_the_process_publishes_is_the_one_the_library_builds() {
    let sandbox = Sandbox::new();
    let published = sandbox.run(&["meta", "schema", "--command", "query run"]);
    assert_eq!(
        published.code, 0,
        "the contract is served: {}",
        published.err
    );

    assert_eq!(
        published.answer()["data"],
        contract_of("query run"),
        "the process and the library disagree about the contract of `query run`"
    );
}