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
//! Proving that every published command is reachable from the argument list.
//!
//! # Why this file exists
//!
//! A command can be written, tested and complete, and still be unreachable
//! because nothing routes to it. The unit tests cannot see that: they call the
//! command directly, which is precisely the step the caller cannot take. This
//! file starts where the caller starts.
//!
//! The contract of a command is answered without reaching a server, so every
//! leaf can be driven here with nothing configured and no server running.

// 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 support::{published_leaves, Sandbox};

/// The refusal a command that is published but not routed answers with.
const NOT_ROUTED: &str = "usage.served_without_a_connection";

/// FR-053. Every command the surface describes really answers its own contract,
/// so the description corresponds to what the build serves.
///
/// Every published command answers its own contract, with no server anywhere.
///
/// This is the proof the surface really is reachable. A command that is
/// published and not routed fails here, however complete its own tests are.
#[test]
fn every_published_command_is_reachable() {
    let sandbox = Sandbox::new();
    let leaves = published_leaves(&sandbox);
    assert!(leaves.len() >= 59, "the whole surface must be published");

    let mut unreachable = Vec::new();
    for leaf in &leaves {
        let mut args: Vec<&str> = vec!["--print-schema"];
        args.extend(leaf.split(' '));
        let outcome = sandbox.run(&args);

        if outcome.code != 0 || outcome.out.is_empty() {
            unreachable.push(format!(
                "{leaf} -> exit {} {}",
                outcome.code,
                outcome.err.trim()
            ));
        }
    }

    assert!(
        unreachable.is_empty(),
        "these published commands cannot be reached:\n{}",
        unreachable.join("\n")
    );
}

/// FR-053. The state the description carries is checked against the build, so
/// the surface never claims a command the product does not serve.
///
/// A command the surface declares as served must really be served.
///
/// The state travels with the command so the published surface never claims
/// more than the build delivers. This is what proves the claim.
#[test]
fn nothing_declared_served_answers_that_it_is_not_routed() {
    let sandbox = Sandbox::new();
    let mut lying = Vec::new();

    for row in sandbox.run(&["meta", "commands"]).rows() {
        let (Some(name), Some(state)) = (row["name"].as_str(), row["state"].as_str()) else {
            continue;
        };
        if state != "served" {
            continue;
        }

        let mut args: Vec<&str> = vec!["--print-schema"];
        args.extend(name.split(' '));
        let outcome = sandbox.run(&args);
        if outcome.code != 0 || outcome.err.contains(NOT_ROUTED) {
            lying.push(name.to_owned());
        }
    }

    assert!(
        lying.is_empty(),
        "these commands are declared served and are not: {lying:?}"
    );
}

/// FR-073 and FR-069. Resolving where a column comes from is read from the
/// statement with no connection open, and a statement kept under a name is
/// saved, listed and removed without one either.
///
/// The commands that reach no server must answer with nothing configured.
///
/// Resolving where a result column comes from is read from the statement's own
/// tree, and keeping a statement under a name only touches the settings
/// location. Neither may cost a connection.
#[test]
fn the_commands_that_need_no_server_answer_without_one() {
    let sandbox = Sandbox::new();

    let lineage = sandbox.run(&["query", "lineage", "SELECT p.total FROM pedidos AS p"]);
    assert_eq!(
        lineage.code, 0,
        "lineage must not need a server: {}",
        lineage.err
    );
    assert_eq!(lineage.answer()["command"], "query lineage");
    assert_eq!(
        lineage.answer()["data"]["rows"][0]["sources"][0]["table"],
        "pedidos"
    );

    let saved = sandbox.run(&[
        "query",
        "named",
        "save",
        "pedidos",
        "SELECT * FROM pedidos WHERE pago = 1",
    ]);
    assert_eq!(
        saved.code, 0,
        "saving must not need a server: {}",
        saved.err
    );

    let listed = sandbox.run(&["query", "named", "list"]);
    assert_eq!(
        listed.code, 0,
        "listing must not need a server: {}",
        listed.err
    );
    assert_eq!(listed.answer()["data"]["rows"][0]["name"], "pedidos");

    let removed = sandbox.run(&["query", "named", "remove", "pedidos"]);
    assert_eq!(
        removed.code, 0,
        "removing must not need a server: {}",
        removed.err
    );
}

/// FR-069. A statement kept under a name is run by that name alone, so the
/// refusal is about the missing destination and never about the missing text.
///
/// Running a statement kept under a name does need a server, and the refusal
/// must say what is missing rather than pretending the command is unknown.
#[test]
fn running_a_kept_statement_asks_for_a_destination() {
    let sandbox = Sandbox::new();
    let outcome = sandbox.run(&["query", "named", "run", "pedidos"]);
    assert_ne!(outcome.code, 0);
    assert_ne!(
        outcome.code(),
        NOT_ROUTED,
        "needing a destination is not the same as not being routed"
    );
}

/// FR-053. The described tree is the whole tree, counted and free of a command
/// published twice.
///
/// The surface the map publishes and the surface the tree carries are one.
#[test]
fn the_published_surface_carries_the_expected_count() {
    let sandbox = Sandbox::new();
    let leaves = published_leaves(&sandbox);

    // `query named` carries four actions of its own, and the map counts each
    // of them, so the tree is wider than the fifty-nine the annex lists.
    assert_eq!(leaves.len(), 63, "published leaves: {leaves:?}");

    let mut sorted = leaves.clone();
    sorted.sort();
    sorted.dedup();
    assert_eq!(sorted.len(), leaves.len(), "a command is published twice");
}

/// FR-064. Two identical invocations write identical bytes on the primary
/// channel, so comparing runs never accuses a difference the product invented.
///
/// The same invocation must produce the same bytes, or two runs cannot be
/// compared without storing the data.
#[test]
fn the_published_surface_is_byte_for_byte_stable() {
    let sandbox = Sandbox::new();
    let first = sandbox.run(&["meta", "commands"]).out;
    let second = sandbox.run(&["meta", "commands"]).out;
    assert_eq!(first, second);
}

/// FR-047, FR-048 and FR-050. A missing destination is the configuration class,
/// carries its own stable code, exits four, and leaves the primary channel
/// untouched.
///
/// A command that needs a destination says so through the configuration
/// category, and never through a network failure it never attempted.
#[test]
fn a_missing_destination_is_a_configuration_failure() {
    let sandbox = Sandbox::new();
    let outcome = sandbox.run(&["schema", "tables"]);
    assert_eq!(outcome.code, 4, "stderr: {}", outcome.err);
    assert_eq!(outcome.code(), "profile.no_default");
    assert!(
        outcome.out.is_empty(),
        "a failure must never reach the primary channel"
    );
}

/// A command that redeclares a name the global flags already own.
///
/// EMPTY, and asserted by equality so it stays that way. Each entry would be a
/// defect rather than a decision: two declarations of one long name are matched
/// by the argument layer as a SINGLE argument, so one word typed once arrives
/// in two fields and two readers act on it. The argument layer accepts that
/// without a conflict, a panic or a warning, which is why the refusal has to
/// live here.
///
/// `data export` is the reason this test exists, and the history is worth
/// carrying. It declared `--output` against the global of the same name, wrote
/// the copy to that path, and then the single output destination in
/// `src/lib.rs` wrote its receipt over the same path — so the file a caller
/// asked their dump into ended up holding the account of having written it, at
/// exit 0 with nothing said. Its own destination is `--to` now, and
/// `the_two_destinations_of_a_copy_stay_independent` proves the two stay apart.
///
/// Sixteen further declarations of `--database` were removed rather than
/// listed. They were harmless only because both readers happened to agree, and
/// a coincidence is not a guarantee.
const REDECLARES_A_GLOBAL_NAME: &[&str] = &[];

/// No command redeclares a name the global flags already own.
///
/// # Why this is worth a test
///
/// Two independent declarations of the same long name are matched by the
/// argument layer as ONE argument, and the value then reaches both fields. A
/// command that read its own field would act on a value the global path is
/// acting on too — `meta manual` declared `--output` this way, and the two
/// readers would have written the same destination twice, the second erasing
/// the first with its own receipt. The help was wrong as well, promising what
/// the local description said and delivering what the global path does.
///
/// Nothing in the argument layer refuses this, so the refusal lives here.
#[test]
fn no_command_redeclares_a_name_the_global_flags_already_own() {
    let root = <mariadb_cli::cli::Cli as clap::CommandFactory>::command();

    // A global argument is declared once and offered everywhere, so the names
    // to protect are exactly the ones the root declares as global.
    let owned: std::collections::BTreeSet<String> = root
        .get_arguments()
        .filter(|argument| argument.is_global_set())
        .filter_map(|argument| argument.get_long().map(ToOwned::to_owned))
        .collect();
    assert!(
        owned.contains("output"),
        "the global flags must own --output, or this test proves nothing"
    );

    let mut clashes = Vec::new();
    walk(&root, &mut Vec::new(), &owned, &mut clashes);
    clashes.sort_unstable();

    let mut declared = REDECLARES_A_GLOBAL_NAME.to_vec();
    declared.sort_unstable();

    assert_eq!(
        clashes, declared,
        "these commands redeclare a name the global flags already own"
    );
}

/// The one global `--database` still selects on every family that used to
/// declare its own.
///
/// Sixteen commands declared `--database` against the global, so one word typed
/// once arrived in two fields and two readers acted on it. Removing sixteen
/// declarations could have removed the flag from those commands by accident,
/// and the argument layer would have said nothing: an unknown flag is a usage
/// failure at run time, not a compile failure. So the flag is driven on one
/// command per family and its value is read back off the global.
#[test]
fn the_one_database_flag_still_selects_on_every_family() {
    use clap::Parser as _;

    for command in [
        vec!["schema", "tables"],
        vec!["query", "sample", "--table", "orders"],
        vec!["data", "export", "--to", "/tmp/copy.sql"],
        vec!["history", "tables"],
    ] {
        let argv: Vec<String> = std::iter::once("mariadb-cli".to_owned())
            .chain(command.iter().map(|piece| (*piece).to_owned()))
            .chain(["--database".to_owned(), "sales".to_owned()])
            .collect();

        let cli = mariadb_cli::cli::Cli::try_parse_from(argv).unwrap_or_else(|refused| {
            panic!(
                "`{}` no longer accepts --database: {refused}",
                command.join(" ")
            )
        });

        assert_eq!(
            cli.globals.destination.database.as_deref(),
            Some("sales"),
            "`{}` accepted --database and it reached nothing",
            command.join(" ")
        );
    }
}

/// FR-041. The destination the receipt is written to is the global one, and it
/// stays apart from the destination the copy itself was asked into.
///
/// A copy and the answer about the copy go to two different files.
///
/// This is the proof that the repair took. The two destinations were one
/// argument, so the receipt landed on the copy and erased it. They are separate
/// declarations now, and the only way to show that is to name both at once and
/// watch them stay apart.
#[test]
fn the_two_destinations_of_a_copy_stay_independent() {
    use clap::Parser as _;

    let command_line = [
        "mariadb-cli",
        "data",
        "export",
        "--to",
        "/tmp/copy.sql",
        "--output",
        "/tmp/receipt.json",
    ];
    let cli = mariadb_cli::cli::Cli::try_parse_from(command_line.iter().map(ToString::to_string))
        .expect("the sample invocation parses");

    let mariadb_cli::cli::Command::Data(mariadb_cli::cli::data::DataCommand::Export(args)) =
        &cli.command
    else {
        panic!("the sample invocation is a copy");
    };

    assert_eq!(
        args.to.as_deref(),
        Some(std::path::Path::new("/tmp/copy.sql")),
        "the copy goes where the command was told"
    );
    assert_eq!(
        cli.globals.output.output.as_deref(),
        Some(std::path::Path::new("/tmp/receipt.json")),
        "and the receipt goes somewhere else entirely"
    );
    assert_ne!(
        args.to.as_deref(),
        cli.globals.output.output.as_deref(),
        "one word typed once must no longer reach both"
    );
}

/// Walks every command below this one, collecting redeclared global names.
fn walk(
    command: &clap::Command,
    path: &mut Vec<String>,
    owned: &std::collections::BTreeSet<String>,
    clashes: &mut Vec<String>,
) {
    for child in command.get_subcommands() {
        path.push(child.get_name().to_owned());

        for argument in child.get_arguments() {
            // The global ones are the same declaration reaching every command,
            // which is the whole point of them, so they are never a clash.
            if argument.is_global_set() {
                continue;
            }
            if let Some(long) = argument.get_long() {
                if owned.contains(long) {
                    clashes.push(format!("{} redeclares --{long}", path.join(" ")));
                }
            }
        }

        walk(child, path, owned, clashes);
        path.pop();
    }
}

/// Every command that spells a flag the same way accepts the same forms.
///
/// # The defect this was written from
///
/// `conn add` and `conn edit` both offer `--pin-database`, `--read-only-profile`
/// and `--require-tls`. On `conn edit` all three took an optional value, because
/// an edit needs a third state for "not mentioned". On `conn add` only
/// `--require-tls` did. So on one command, three flags that all carry a truth
/// value disagreed about whether a value could follow, and
/// `conn add p --pin-database true` ended in 2 with `unexpected argument
/// 'true'` — a message that names the value rather than the flag, and leaves
/// the caller to work out by trial which of three siblings takes one.
///
/// Nothing caught it because each declaration was correct where it stood. The
/// disagreement only exists between them, and no reader compares siblings.
///
/// # Why the rule is about names rather than about truth values
///
/// Writing this as "every boolean flag must agree" would fix the instance and
/// leave the class: the caller does not learn a flag as a type, they learn it
/// as a spelling, and a spelling that works on one command and fails on its
/// neighbour is the same surprise whatever the value happens to be. So the rule
/// is the wider one, and it costs nothing extra to hold.
///
/// A shared name is allowed to differ where the difference is declared below.
///
/// `--table` is the one entry, and it is a real difference rather than an
/// oversight: `data export` restricts a walk to several tables and takes a list
/// separated by commas, while everywhere else `--table` names the one table the
/// command is about. The plurality is the difference, and collapsing it would
/// either take a capability away from export or hand every other command a list
/// it has no use for.
///
/// The trap that comes with it was measured rather than assumed:
/// `data export --table a,b` reads two names, and `data import --table a,b`
/// reads one table called `a,b`. That stays visible instead of being silent —
/// import now ends in 8 with the name it was given printed in the cause chain,
/// so a caller who carried the comma across from export is told which table was
/// looked for. Before the refusal was fixed it ended in 0.
const SPELLED_TWO_WAYS: &[&str] = &["table {\"unset/append\", \"unset/set\"}"];

/// The forms one flag accepts, as the argument layer holds them.
///
/// Built from the accessors rather than from how the argument library prints
/// its own types. A `Debug` rendering is a convenience nobody promised to keep,
/// and the risk is not that it changes — that would fail here, loudly. It is
/// that a change makes two different shapes print the same, after which this
/// walk stops telling them apart and stays green for good. The numbers and the
/// spelled-out action cannot collapse that way.
fn accepted_forms(argument: &clap::Arg) -> String {
    let takes = argument.get_num_args().map_or_else(
        || "unset".to_owned(),
        |range| format!("{}..={}", range.min_values(), range.max_values()),
    );
    let action = match argument.get_action() {
        clap::ArgAction::Set => "set",
        clap::ArgAction::Append => "append",
        clap::ArgAction::SetTrue => "set-true",
        clap::ArgAction::SetFalse => "set-false",
        clap::ArgAction::Count => "count",
        clap::ArgAction::Help | clap::ArgAction::HelpShort | clap::ArgAction::HelpLong => "help",
        clap::ArgAction::Version => "version",
        // Named rather than swallowed: a new action folded into a catch-all
        // would read as equal to every other new one, which is the collapse the
        // whole function exists to avoid.
        other => panic!("an action this walk does not name yet: {other:?}"),
    };
    format!("{takes}/{action}")
}

/// No flag name means two different shapes on two different commands.
#[test]
fn a_flag_spelled_the_same_on_two_commands_accepts_the_same_forms() {
    let root = <mariadb_cli::cli::Cli as clap::CommandFactory>::command();
    let mut seen: std::collections::BTreeMap<String, std::collections::BTreeSet<String>> =
        std::collections::BTreeMap::new();
    gather_forms(&root, &mut seen);

    // Named rather than assumed: a walk that reached nothing would report no
    // disagreement and pass, which is the cheapest way for this to stop working.
    assert!(
        seen.contains_key("pin-database"),
        "the walk must reach --pin-database, or this test proves nothing"
    );

    let mut split: Vec<String> = seen
        .into_iter()
        .filter(|(_, forms)| forms.len() > 1)
        .map(|(name, forms)| format!("{name} {forms:?}"))
        .collect();
    split.sort_unstable();

    let mut declared: Vec<String> = SPELLED_TWO_WAYS
        .iter()
        .map(|name| (*name).to_owned())
        .collect();
    declared.sort_unstable();

    assert_eq!(
        split, declared,
        "these flags are spelled the same on more than one command and accept \
         different forms, so a caller who learns one is wrong on the other"
    );
}

/// Records the forms every long flag is declared with, over the whole tree.
fn gather_forms(
    command: &clap::Command,
    seen: &mut std::collections::BTreeMap<String, std::collections::BTreeSet<String>>,
) {
    for argument in command.get_arguments() {
        // A global is one declaration offered everywhere, so it cannot disagree
        // with itself and counting it once per command would only add noise.
        if argument.is_global_set() {
            continue;
        }
        if let Some(long) = argument.get_long() {
            seen.entry(long.to_owned())
                .or_default()
                .insert(accepted_forms(argument));
        }
    }
    for child in command.get_subcommands() {
        gather_forms(child, seen);
    }
}