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
//! The global flags, valid on every command.
//!
//! A global flag absent from this file does not exist in the product. Flags
//! that belong to a single command live with that command and are published
//! through its own contract.

use clap::{Args, ValueEnum};

/// How the primary channel is shaped.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "lower")]
pub enum OutputFormat {
    /// One document per invocation.
    Json,
    /// One document per line, for continuous streaming.
    Ndjson,
    /// Tab separated values.
    Tsv,
    /// Plain text for a human reader.
    Text,
}

/// What a change count means.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "lower")]
pub enum RowCountMode {
    /// Rows the restriction matched.
    Matched,
    /// Rows the server actually altered.
    Changed,
}

/// Whether the network channel is compressed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "lower")]
pub enum Compress {
    /// Let the negotiation decide.
    Auto,
    /// Always compress.
    Always,
    /// Never compress.
    Never,
}

/// Which destination the invocation talks to.
#[derive(Debug, Clone, Args)]
pub struct DestinationFlags {
    /// Profile to use; defaults to the one marked as default.
    #[arg(long, global = true, value_name = "NAME")]
    pub profile: Option<String>,

    /// Database this operation targets; defaults to the profile's database.
    #[arg(long, global = true, value_name = "NAME")]
    pub database: Option<String>,

    /// Destination as a single text, instead of a profile.
    ///
    /// The text travels in the command line, so everything in it — including a
    /// password — is readable by anything that can see this process, and stays
    /// readable in whatever recorded the call. A profile keeps the secret in a
    /// file only its owner can read and puts a name here instead, which is the
    /// same designation with none of the exposure.
    #[arg(long, global = true, value_name = "TEXT", conflicts_with = "profile")]
    pub dsn: Option<String>,

    /// Run against every stored profile.
    #[arg(long, global = true, conflicts_with_all = ["profile", "dsn"])]
    pub all_profiles: bool,
}

impl DestinationFlags {
    /// Where the destination of this invocation was decided.
    ///
    /// Read from the call alone, so it is known before any store is opened and
    /// before any connection is attempted. That is what lets a change be
    /// refused for an unwritten target without paying a round trip for the
    /// refusal.
    #[must_use]
    pub const fn source(&self) -> crate::output::envelope::TargetSource {
        if self.dsn.is_some() {
            crate::output::envelope::TargetSource::Dsn
        } else if self.profile.is_some() {
            crate::output::envelope::TargetSource::Argv
        } else if self.all_profiles {
            // A rule that names several destinations is still the call naming
            // them. Reporting this as inherited was wrong twice over: it told
            // the caller that something else had chosen, and it made the guard
            // against an unwritten target refuse a call that had written one —
            // leaving `conn.require_explicit_target` off as the only way
            // through, which turns the guard off for every other command too.
            crate::output::envelope::TargetSource::Selector
        } else {
            crate::output::envelope::TargetSource::Config
        }
    }
}

/// How the answer is shaped before it leaves.
// Allowed: a command line offers independent switches, and clap builds
// this record field by field from them. Folding them into a nested
// type would publish a grouping the manual does not have and change
// the path every reader writes, for no gain to the caller.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Args)]
pub struct OutputFlags {
    /// Shape of the primary channel.
    #[arg(long, global = true, value_enum, value_name = "FORMAT")]
    pub output_format: Option<OutputFormat>,

    /// Emit the output contract and stop, without reaching the server.
    #[arg(long, global = true)]
    pub print_schema: bool,

    /// Keep only these fields, separated by commas.
    ///
    /// `--fields` is the same flag under the other name agent tooling reaches
    /// for. An alias adds a spelling and removes none, so the contract keeps
    /// naming one flag while a caller who wrote the other is answered instead
    /// of refused.
    #[arg(
        long,
        visible_alias = "fields",
        global = true,
        value_name = "FIELDS",
        value_delimiter = ','
    )]
    pub select: Vec<String>,

    /// Keep only rows passing the test; repeatable, joined by conjunction.
    #[arg(long, global = true, value_name = "EXPR")]
    pub filter: Vec<String>,

    /// Order ascending by this field.
    #[arg(long, global = true, value_name = "FIELD")]
    pub sort: Option<String>,

    /// Drop later rows repeating this field's value.
    #[arg(long, global = true, value_name = "FIELD")]
    pub dedupe_by: Option<String>,

    /// Return the count instead of the rows.
    #[arg(long, global = true)]
    pub count_only: bool,

    /// Ceiling on returned rows.
    ///
    /// `-n` is the short form the same tooling writes. It is a second spelling
    /// of this one flag and never a second ceiling, so the two cannot disagree.
    #[arg(short = 'n', long, global = true, value_name = "N")]
    pub limit: Option<usize>,

    /// Continue from the previous page.
    #[arg(long, global = true, value_name = "MARK")]
    pub cursor: Option<String>,

    /// Replace credential-shaped text inside cells with a fixed mark.
    #[arg(long, global = true)]
    pub redact: bool,

    /// Shorten any cell above this many characters.
    #[arg(long, global = true, value_name = "N")]
    pub truncate_cell: Option<usize>,

    /// Ceiling on total volume; whole rows are dropped to fit.
    #[arg(long, global = true, value_name = "N")]
    pub max_output_bytes: Option<usize>,

    /// Return a summary instead of the whole set.
    #[arg(long, global = true)]
    pub summary: bool,

    /// Write the result to a file instead of the primary channel.
    #[arg(long, global = true, value_name = "FILE")]
    pub output: Option<std::path::PathBuf>,

    /// Append the signature of the result.
    #[arg(long, global = true)]
    pub checksum: bool,

    /// What a change count means.
    #[arg(long, global = true, value_enum, value_name = "MODE")]
    pub row_count: Option<RowCountMode>,
}

/// Time and size budgets.
#[derive(Debug, Clone, Args)]
pub struct LimitFlags {
    /// Ceiling for one operation, in seconds.
    #[arg(long, global = true, value_name = "SECS")]
    pub timeout: Option<u64>,

    /// Ceiling for opening the connection, in seconds.
    #[arg(long, global = true, value_name = "SECS")]
    pub connect_timeout: Option<u64>,

    /// Extra attempts on a repeatable failure.
    #[arg(long, global = true, value_name = "N")]
    pub retries: Option<u32>,

    /// Ceiling on simultaneous internal work.
    #[arg(long, global = true, value_name = "N")]
    pub max_concurrency: Option<usize>,

    /// Whether the network channel is compressed.
    #[arg(long, global = true, value_enum, value_name = "MODE")]
    pub compress: Option<Compress>,
}

/// Guards against unintended change.
// Allowed: a command line offers independent switches, and clap builds
// this record field by field from them. Folding them into a nested
// type would publish a grouping the manual does not have and change
// the path every reader writes, for no gain to the caller.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Args)]
pub struct SafetyFlags {
    /// Refuse any change before opening the connection.
    #[arg(long, global = true)]
    pub read_only: bool,

    /// Confirm a destructive operation.
    ///
    /// `--force` is the same flag under the name other tools use for the same
    /// act of confirming. It is deliberately NOT a way past any guard: an
    /// invocation that refuses every change still refuses one, a statement with
    /// no restriction is still refused, and a command with no simulation still
    /// says so. What this flag settles is that the caller meant it, and nothing
    /// else, whichever of the two names was written.
    #[arg(long, short = 'y', visible_alias = "force", global = true)]
    pub yes: bool,

    /// Show what would be done without doing it.
    #[arg(long, global = true)]
    pub dry_run: bool,

    /// Ceiling on rows one change may affect.
    #[arg(long, global = true, value_name = "N")]
    pub max_affected: Option<u64>,

    /// Refuse any question and fail instead of waiting.
    #[arg(long, global = true)]
    pub no_input: bool,

    /// Take the risk of an unverified server certificate, for this invocation.
    ///
    /// A stored key alone does not turn certificate verification off. The
    /// setting says which level to check at; this says the caller knows what
    /// checking at that level leaves open. Requiring both is what stops a
    /// configuration file written months ago, for a laboratory server, from
    /// quietly following the caller to a real one.
    #[arg(long, global = true)]
    pub accept_unverified_tls: bool,
}

/// The auxiliary channel.
#[derive(Debug, Clone, Args)]
pub struct DiagnosticFlags {
    /// Silence the auxiliary channel.
    #[arg(long, short = 'q', global = true, conflicts_with = "verbose")]
    pub quiet: bool,

    /// Raise the detail of the auxiliary channel; repeatable.
    #[arg(long, short = 'v', global = true, action = clap::ArgAction::Count)]
    pub verbose: u8,

    /// Remove decoration from the auxiliary channel.
    #[arg(long, global = true)]
    pub no_color: bool,

    /// Force the language of messages.
    #[arg(long, global = true, value_name = "LANG")]
    pub lang: Option<String>,

    /// Use another configuration location.
    #[arg(long, global = true, value_name = "PATH")]
    pub config_dir: Option<std::path::PathBuf>,
}

/// Every global flag, grouped by purpose.
#[derive(Debug, Clone, Args)]
pub struct GlobalFlags {
    /// Which server this invocation talks to.
    #[command(flatten)]
    pub destination: DestinationFlags,
    /// What the answer looks like and how much of it comes back.
    #[command(flatten)]
    pub output: OutputFlags,
    /// The ceilings on time and on simultaneous work.
    #[command(flatten)]
    pub limits: LimitFlags,
    /// What this invocation is allowed to change.
    #[command(flatten)]
    pub safety: SafetyFlags,
    /// What reaches the auxiliary channel, and in which language.
    #[command(flatten)]
    pub diagnostics: DiagnosticFlags,
}

/// Reads the mark that asks for a page after the first.
///
/// The mark is a plain offset written in decimal, and that is the whole design:
/// the encoded cursor was dropped because a caller could neither predict nor
/// construct one. A mark that is not a count is refused here, before anything
/// is sent, so a tampered or mistyped one costs no connection.
///
/// # Errors
///
/// Returns a usage failure when the mark is not a whole count.
fn resume_mark(given: Option<&str>) -> crate::error::Result<Option<usize>> {
    let Some(text) = given else {
        return Ok(None);
    };
    text.trim().parse::<usize>().map(Some).map_err(|_| {
        crate::error::Failure::usage(
            "usage.resume_mark_unreadable",
            format!("`{text}` is not a resume mark"),
        )
        .with_detail("detail", text)
        .with_hint("a mark is the number of rows to pass over, as answered in `next_cursor`")
    })
}

impl GlobalFlags {
    /// Builds the output pipeline these flags describe.
    ///
    /// The stored settings are read here rather than defaulted, because the
    /// ceiling per cell is a published key and the mark on the command line is
    /// only what overrides it. Building the pipeline from the mark alone, as
    /// this once did, made `output.truncate_cell` a setting the product stored,
    /// read back and reported as being in force while cutting nothing.
    ///
    /// # Errors
    ///
    /// Returns a usage failure when a filter expression is malformed, so a
    /// typo is refused rather than silently matching nothing, and a config
    /// failure when a stored value is outside its domain.
    pub fn pipeline(
        &self,
        config: &crate::config::Config,
    ) -> crate::error::Result<crate::output::Pipeline> {
        let filters = self
            .output
            .filter
            .iter()
            .map(|expression| crate::output::Filter::parse(expression))
            .collect::<crate::error::Result<Vec<_>>>()?;

        self.refuses_ordering_by_a_field_it_removed()?;
        self.refuses_a_cell_ceiling_of_nothing()?;

        Ok(crate::output::Pipeline {
            select: self.output.select.clone(),
            filters,
            sort: self.output.sort.clone(),
            dedupe_by: self.output.dedupe_by.clone(),
            cursor: resume_mark(self.output.cursor.as_deref())?,
            limit: self.output.limit,
            count_only: self.output.count_only,
            summary: self.output.summary,
            // The flag turns it on; the stored key turns it on for every call
            // that does not. There is no way to turn it off from the command
            // line once stored, and that asymmetry is deliberate: a caller who
            // decided their answers must never carry a credential should not be
            // able to undo it by forgetting a flag.
            redact: self.output.redact || crate::settings::boolean(config, "output.redact")?,
            truncate_cell: Some(match self.output.truncate_cell {
                Some(asked) => asked,
                None => crate::settings::count(config, "output.truncate_cell")?,
            }),
            max_output_bytes: self.output.max_output_bytes,
            most_frequent_shown: Some(crate::settings::count(
                config,
                "output.most_frequent_shown",
            )?),
        })
    }

    /// Refuses ordering or de-duplicating by a field the projection removed.
    ///
    /// FR-036 states both halves of this and they are not the same case. A
    /// field absent from SOME ROWS is a fact about the data, discovered by
    /// reading it, and those rows sort to the end: tolerating that is right,
    /// because the caller could not have known. A field absent from the
    /// PROJECTION is a fact about the call, known before anything is sent, and
    /// it is the caller contradicting themselves — they asked for the field to
    /// be dropped and for the answer to be arranged by it.
    ///
    /// Tolerating the second was measured doing real harm. `--select key
    /// --sort origin` ended in 0 and moved the first row from `conn.default` to
    /// `conn.default_port`: an order the caller did not ask for, in an answer
    /// that no longer carries the field that produced it, with nothing anywhere
    /// saying so. A caller who mistypes the field gets the same silence.
    ///
    /// Refusing costs the caller one message and refusing early costs no
    /// connection, which is the same trade every other gate in this product
    /// makes when the call contradicts itself.
    ///
    /// # Errors
    ///
    /// Returns a usage failure naming the field and the fields still present.
    /// A cell ceiling of zero is refused rather than quietly ignored.
    ///
    /// # Why this is here and not only on the stored key
    ///
    /// `output.truncate_cell` publishes its domain as a whole number above
    /// zero, and the stored value is checked against it. The flag of the same
    /// name was not, so `--truncate-cell 0` was accepted and did nothing: the
    /// caller asked for every cell to be cut to nothing, the product answered
    /// with whole cells, and said 0.
    ///
    /// A flag accepted and ignored is worse than one refused, because the
    /// caller believes they asked. FR-038 publishes the refusal, and it now
    /// exists on both halves of the same setting rather than one.
    ///
    /// # Errors
    ///
    /// Returns a usage failure naming the value and the domain it left.
    fn refuses_a_cell_ceiling_of_nothing(&self) -> crate::error::Result<()> {
        if self.output.truncate_cell != Some(0) {
            return Ok(());
        }
        Err(crate::error::Failure::usage(
            "usage.cell_ceiling_of_nothing",
            "`--truncate-cell 0` asks for cells cut to nothing",
        )
        .with_detail("domain", "a whole number above zero")
        .with_hint("write a ceiling above zero, or leave the flag out to keep whole cells"))
    }

    fn refuses_ordering_by_a_field_it_removed(&self) -> crate::error::Result<()> {
        if self.output.select.is_empty() {
            return Ok(());
        }
        // Compared as the projection compares them, so a caller is never
        // refused for a difference the projection itself would have ignored.
        let kept = |field: &str| {
            self.output
                .select
                .iter()
                .any(|name| name.trim() == field.trim())
        };

        for (flag, asked) in [
            ("--sort", self.output.sort.as_deref()),
            ("--dedupe-by", self.output.dedupe_by.as_deref()),
        ] {
            let Some(field) = asked else { continue };
            if kept(field) {
                continue;
            }
            return Err(crate::error::Failure::usage(
                "usage.field_not_in_projection",
                format!("`{flag} {field}` names a field `--select` does not keep"),
            )
            .with_detail("field", field)
            .with_detail("kept", self.output.select.join(","))
            .with_hint("add the field to --select, or order by one it keeps"));
        }
        Ok(())
    }

    /// Refuses a profile of the whole set written as a continuous flow.
    ///
    /// FR-040 refuses this combination outright rather than quietly gathering:
    /// a caller who asked for a flow AND for a profile of the whole set asked
    /// for two things that cannot both hold, and silently honouring one of them
    /// would answer a question nobody put.
    ///
    /// The shape is taken as the resolved one rather than read from the mark on
    /// the command line. Reading the mark, as this once did, let a caller who
    /// had stored a line-oriented shape ask for a profile and receive one,
    /// while a caller who wrote the same shape on the command line was refused
    /// — the same request answered two ways by where the shape was written.
    ///
    /// # Errors
    ///
    /// Returns a usage failure when a profile was asked for over a shape that
    /// carries one record per line.
    pub fn refuse_a_profile_over_a_flow(&self, shape: OutputFormat) -> crate::error::Result<()> {
        if self.output.summary && matches!(shape, OutputFormat::Ndjson | OutputFormat::Tsv) {
            return Err(crate::error::Failure::usage(
                "usage.summary_with_a_flow",
                "a profile of the whole set cannot be written as a continuous flow",
            )
            .with_hint("drop --summary, or ask for a shape that carries one answer"));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use clap::Parser as _;

    /// The second spelling of a flag reaches the same field as the first.
    ///
    /// # Why an alias is worth a proof
    ///
    /// An alias is one line of attribute and no code, so nothing fails when it
    /// is dropped: the flag goes on working under its first name and the second
    /// simply stops being accepted, which a caller meets as a usage refusal
    /// rather than as anything a build or a lint would notice.
    ///
    /// The two names exist because the contract publishes one and the tooling
    /// that reaches for this product writes the other. What must never happen
    /// is the pair drifting into two ceilings or two projections that can
    /// disagree, so what is asserted here is that they land in ONE field.
    #[test]
    fn the_second_name_of_a_flag_reaches_the_same_field_as_the_first() {
        let by_first = crate::cli::Cli::try_parse_from([
            "mariadb-cli",
            "--select",
            "a,b",
            "--limit",
            "7",
            "meta",
            "version",
        ])
        .expect("the published spelling parses");
        let by_second = crate::cli::Cli::try_parse_from([
            "mariadb-cli",
            "--fields",
            "a,b",
            "-n",
            "7",
            "meta",
            "version",
        ])
        .expect("the alias parses");

        assert_eq!(
            by_first.globals.output.select, by_second.globals.output.select,
            "`--fields` has to reach the field `--select` reaches"
        );
        assert_eq!(
            by_first.globals.output.limit, by_second.globals.output.limit,
            "`-n` has to reach the field `--limit` reaches"
        );
        assert_eq!(by_second.globals.output.limit, Some(7));
    }

    /// Confirming under the other name confirms, and opens nothing else.
    ///
    /// # The misreading this refuses
    ///
    /// In other tools `--force` means "past the guard", and a caller carrying
    /// that habit would expect it to override a refusal. Here it settles one
    /// question only — that the caller meant the change — so the second half of
    /// this proof is the half that matters: the invocation that refuses every
    /// change goes on refusing with the flag present.
    #[test]
    fn confirming_under_the_other_name_confirms_and_overrides_nothing() {
        let by_first = crate::cli::Cli::try_parse_from(["mariadb-cli", "--yes", "meta", "version"])
            .expect("the published spelling parses");
        let by_second =
            crate::cli::Cli::try_parse_from(["mariadb-cli", "--force", "meta", "version"])
                .expect("the alias parses");
        assert_eq!(by_first.globals.safety.yes, by_second.globals.safety.yes);
        assert!(by_second.globals.safety.yes);

        // The guard it must not open. Read-only is answered before confirmation
        // is ever consulted, so the two cannot trade places.
        let forced = crate::cli::Cli::try_parse_from([
            "mariadb-cli",
            "--force",
            "--read-only",
            "meta",
            "version",
        ])
        .expect("both flags parse together");
        assert!(
            forced.globals.safety.read_only,
            "confirming must not clear the refusal of every change"
        );
    }
}