Skip to main content

mariadb_cli/cli/
globals.rs

1//! The global flags, valid on every command.
2//!
3//! A global flag absent from this file does not exist in the product. Flags
4//! that belong to a single command live with that command and are published
5//! through its own contract.
6
7use clap::{Args, ValueEnum};
8
9/// How the primary channel is shaped.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
11#[value(rename_all = "lower")]
12pub enum OutputFormat {
13    /// One document per invocation.
14    Json,
15    /// One document per line, for continuous streaming.
16    Ndjson,
17    /// Tab separated values.
18    Tsv,
19    /// Plain text for a human reader.
20    Text,
21}
22
23/// What a change count means.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
25#[value(rename_all = "lower")]
26pub enum RowCountMode {
27    /// Rows the restriction matched.
28    Matched,
29    /// Rows the server actually altered.
30    Changed,
31}
32
33/// Whether the network channel is compressed.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
35#[value(rename_all = "lower")]
36pub enum Compress {
37    /// Let the negotiation decide.
38    Auto,
39    /// Always compress.
40    Always,
41    /// Never compress.
42    Never,
43}
44
45/// Which destination the invocation talks to.
46#[derive(Debug, Clone, Args)]
47pub struct DestinationFlags {
48    /// Profile to use; defaults to the one marked as default.
49    #[arg(long, global = true, value_name = "NAME")]
50    pub profile: Option<String>,
51
52    /// Database this operation targets; defaults to the profile's database.
53    #[arg(long, global = true, value_name = "NAME")]
54    pub database: Option<String>,
55
56    /// Destination as a single text, instead of a profile.
57    ///
58    /// The text travels in the command line, so everything in it — including a
59    /// password — is readable by anything that can see this process, and stays
60    /// readable in whatever recorded the call. A profile keeps the secret in a
61    /// file only its owner can read and puts a name here instead, which is the
62    /// same designation with none of the exposure.
63    #[arg(long, global = true, value_name = "TEXT", conflicts_with = "profile")]
64    pub dsn: Option<String>,
65
66    /// Run against every stored profile.
67    #[arg(long, global = true, conflicts_with_all = ["profile", "dsn"])]
68    pub all_profiles: bool,
69}
70
71impl DestinationFlags {
72    /// Where the destination of this invocation was decided.
73    ///
74    /// Read from the call alone, so it is known before any store is opened and
75    /// before any connection is attempted. That is what lets a change be
76    /// refused for an unwritten target without paying a round trip for the
77    /// refusal.
78    #[must_use]
79    pub const fn source(&self) -> crate::output::envelope::TargetSource {
80        if self.dsn.is_some() {
81            crate::output::envelope::TargetSource::Dsn
82        } else if self.profile.is_some() {
83            crate::output::envelope::TargetSource::Argv
84        } else if self.all_profiles {
85            // A rule that names several destinations is still the call naming
86            // them. Reporting this as inherited was wrong twice over: it told
87            // the caller that something else had chosen, and it made the guard
88            // against an unwritten target refuse a call that had written one —
89            // leaving `conn.require_explicit_target` off as the only way
90            // through, which turns the guard off for every other command too.
91            crate::output::envelope::TargetSource::Selector
92        } else {
93            crate::output::envelope::TargetSource::Config
94        }
95    }
96}
97
98/// How the answer is shaped before it leaves.
99// Allowed: a command line offers independent switches, and clap builds
100// this record field by field from them. Folding them into a nested
101// type would publish a grouping the manual does not have and change
102// the path every reader writes, for no gain to the caller.
103#[allow(clippy::struct_excessive_bools)]
104#[derive(Debug, Clone, Args)]
105pub struct OutputFlags {
106    /// Shape of the primary channel.
107    #[arg(long, global = true, value_enum, value_name = "FORMAT")]
108    pub output_format: Option<OutputFormat>,
109
110    /// Emit the output contract and stop, without reaching the server.
111    #[arg(long, global = true)]
112    pub print_schema: bool,
113
114    /// Keep only these fields, separated by commas.
115    ///
116    /// `--fields` is the same flag under the other name agent tooling reaches
117    /// for. An alias adds a spelling and removes none, so the contract keeps
118    /// naming one flag while a caller who wrote the other is answered instead
119    /// of refused.
120    #[arg(
121        long,
122        visible_alias = "fields",
123        global = true,
124        value_name = "FIELDS",
125        value_delimiter = ','
126    )]
127    pub select: Vec<String>,
128
129    /// Keep only rows passing the test; repeatable, joined by conjunction.
130    #[arg(long, global = true, value_name = "EXPR")]
131    pub filter: Vec<String>,
132
133    /// Order ascending by this field.
134    #[arg(long, global = true, value_name = "FIELD")]
135    pub sort: Option<String>,
136
137    /// Drop later rows repeating this field's value.
138    #[arg(long, global = true, value_name = "FIELD")]
139    pub dedupe_by: Option<String>,
140
141    /// Return the count instead of the rows.
142    #[arg(long, global = true)]
143    pub count_only: bool,
144
145    /// Ceiling on returned rows.
146    ///
147    /// `-n` is the short form the same tooling writes. It is a second spelling
148    /// of this one flag and never a second ceiling, so the two cannot disagree.
149    #[arg(short = 'n', long, global = true, value_name = "N")]
150    pub limit: Option<usize>,
151
152    /// Continue from the previous page.
153    #[arg(long, global = true, value_name = "MARK")]
154    pub cursor: Option<String>,
155
156    /// Replace credential-shaped text inside cells with a fixed mark.
157    #[arg(long, global = true)]
158    pub redact: bool,
159
160    /// Shorten any cell above this many characters.
161    #[arg(long, global = true, value_name = "N")]
162    pub truncate_cell: Option<usize>,
163
164    /// Ceiling on total volume; whole rows are dropped to fit.
165    #[arg(long, global = true, value_name = "N")]
166    pub max_output_bytes: Option<usize>,
167
168    /// Return a summary instead of the whole set.
169    #[arg(long, global = true)]
170    pub summary: bool,
171
172    /// Write the result to a file instead of the primary channel.
173    #[arg(long, global = true, value_name = "FILE")]
174    pub output: Option<std::path::PathBuf>,
175
176    /// Append the signature of the result.
177    #[arg(long, global = true)]
178    pub checksum: bool,
179
180    /// What a change count means.
181    #[arg(long, global = true, value_enum, value_name = "MODE")]
182    pub row_count: Option<RowCountMode>,
183}
184
185/// Time and size budgets.
186#[derive(Debug, Clone, Args)]
187pub struct LimitFlags {
188    /// Ceiling for one operation, in seconds.
189    #[arg(long, global = true, value_name = "SECS")]
190    pub timeout: Option<u64>,
191
192    /// Ceiling for opening the connection, in seconds.
193    #[arg(long, global = true, value_name = "SECS")]
194    pub connect_timeout: Option<u64>,
195
196    /// Extra attempts on a repeatable failure.
197    #[arg(long, global = true, value_name = "N")]
198    pub retries: Option<u32>,
199
200    /// Ceiling on simultaneous internal work.
201    #[arg(long, global = true, value_name = "N")]
202    pub max_concurrency: Option<usize>,
203
204    /// Whether the network channel is compressed.
205    #[arg(long, global = true, value_enum, value_name = "MODE")]
206    pub compress: Option<Compress>,
207}
208
209/// Guards against unintended change.
210// Allowed: a command line offers independent switches, and clap builds
211// this record field by field from them. Folding them into a nested
212// type would publish a grouping the manual does not have and change
213// the path every reader writes, for no gain to the caller.
214#[allow(clippy::struct_excessive_bools)]
215#[derive(Debug, Clone, Args)]
216pub struct SafetyFlags {
217    /// Refuse any change before opening the connection.
218    #[arg(long, global = true)]
219    pub read_only: bool,
220
221    /// Confirm a destructive operation.
222    ///
223    /// `--force` is the same flag under the name other tools use for the same
224    /// act of confirming. It is deliberately NOT a way past any guard: an
225    /// invocation that refuses every change still refuses one, a statement with
226    /// no restriction is still refused, and a command with no simulation still
227    /// says so. What this flag settles is that the caller meant it, and nothing
228    /// else, whichever of the two names was written.
229    #[arg(long, short = 'y', visible_alias = "force", global = true)]
230    pub yes: bool,
231
232    /// Show what would be done without doing it.
233    #[arg(long, global = true)]
234    pub dry_run: bool,
235
236    /// Ceiling on rows one change may affect.
237    #[arg(long, global = true, value_name = "N")]
238    pub max_affected: Option<u64>,
239
240    /// Refuse any question and fail instead of waiting.
241    #[arg(long, global = true)]
242    pub no_input: bool,
243
244    /// Take the risk of an unverified server certificate, for this invocation.
245    ///
246    /// A stored key alone does not turn certificate verification off. The
247    /// setting says which level to check at; this says the caller knows what
248    /// checking at that level leaves open. Requiring both is what stops a
249    /// configuration file written months ago, for a laboratory server, from
250    /// quietly following the caller to a real one.
251    #[arg(long, global = true)]
252    pub accept_unverified_tls: bool,
253}
254
255/// The auxiliary channel.
256#[derive(Debug, Clone, Args)]
257pub struct DiagnosticFlags {
258    /// Silence the auxiliary channel.
259    #[arg(long, short = 'q', global = true, conflicts_with = "verbose")]
260    pub quiet: bool,
261
262    /// Raise the detail of the auxiliary channel; repeatable.
263    #[arg(long, short = 'v', global = true, action = clap::ArgAction::Count)]
264    pub verbose: u8,
265
266    /// Remove decoration from the auxiliary channel.
267    #[arg(long, global = true)]
268    pub no_color: bool,
269
270    /// Force the language of messages.
271    #[arg(long, global = true, value_name = "LANG")]
272    pub lang: Option<String>,
273
274    /// Use another configuration location.
275    #[arg(long, global = true, value_name = "PATH")]
276    pub config_dir: Option<std::path::PathBuf>,
277}
278
279/// Every global flag, grouped by purpose.
280#[derive(Debug, Clone, Args)]
281pub struct GlobalFlags {
282    /// Which server this invocation talks to.
283    #[command(flatten)]
284    pub destination: DestinationFlags,
285    /// What the answer looks like and how much of it comes back.
286    #[command(flatten)]
287    pub output: OutputFlags,
288    /// The ceilings on time and on simultaneous work.
289    #[command(flatten)]
290    pub limits: LimitFlags,
291    /// What this invocation is allowed to change.
292    #[command(flatten)]
293    pub safety: SafetyFlags,
294    /// What reaches the auxiliary channel, and in which language.
295    #[command(flatten)]
296    pub diagnostics: DiagnosticFlags,
297}
298
299/// Reads the mark that asks for a page after the first.
300///
301/// The mark is a plain offset written in decimal, and that is the whole design:
302/// the encoded cursor was dropped because a caller could neither predict nor
303/// construct one. A mark that is not a count is refused here, before anything
304/// is sent, so a tampered or mistyped one costs no connection.
305///
306/// # Errors
307///
308/// Returns a usage failure when the mark is not a whole count.
309fn resume_mark(given: Option<&str>) -> crate::error::Result<Option<usize>> {
310    let Some(text) = given else {
311        return Ok(None);
312    };
313    text.trim().parse::<usize>().map(Some).map_err(|_| {
314        crate::error::Failure::usage(
315            "usage.resume_mark_unreadable",
316            format!("`{text}` is not a resume mark"),
317        )
318        .with_detail("detail", text)
319        .with_hint("a mark is the number of rows to pass over, as answered in `next_cursor`")
320    })
321}
322
323impl GlobalFlags {
324    /// Builds the output pipeline these flags describe.
325    ///
326    /// The stored settings are read here rather than defaulted, because the
327    /// ceiling per cell is a published key and the mark on the command line is
328    /// only what overrides it. Building the pipeline from the mark alone, as
329    /// this once did, made `output.truncate_cell` a setting the product stored,
330    /// read back and reported as being in force while cutting nothing.
331    ///
332    /// # Errors
333    ///
334    /// Returns a usage failure when a filter expression is malformed, so a
335    /// typo is refused rather than silently matching nothing, and a config
336    /// failure when a stored value is outside its domain.
337    pub fn pipeline(
338        &self,
339        config: &crate::config::Config,
340    ) -> crate::error::Result<crate::output::Pipeline> {
341        let filters = self
342            .output
343            .filter
344            .iter()
345            .map(|expression| crate::output::Filter::parse(expression))
346            .collect::<crate::error::Result<Vec<_>>>()?;
347
348        self.refuses_ordering_by_a_field_it_removed()?;
349        self.refuses_a_cell_ceiling_of_nothing()?;
350
351        Ok(crate::output::Pipeline {
352            select: self.output.select.clone(),
353            filters,
354            sort: self.output.sort.clone(),
355            dedupe_by: self.output.dedupe_by.clone(),
356            cursor: resume_mark(self.output.cursor.as_deref())?,
357            limit: self.output.limit,
358            count_only: self.output.count_only,
359            summary: self.output.summary,
360            // The flag turns it on; the stored key turns it on for every call
361            // that does not. There is no way to turn it off from the command
362            // line once stored, and that asymmetry is deliberate: a caller who
363            // decided their answers must never carry a credential should not be
364            // able to undo it by forgetting a flag.
365            redact: self.output.redact || crate::settings::boolean(config, "output.redact")?,
366            truncate_cell: Some(match self.output.truncate_cell {
367                Some(asked) => asked,
368                None => crate::settings::count(config, "output.truncate_cell")?,
369            }),
370            max_output_bytes: self.output.max_output_bytes,
371            most_frequent_shown: Some(crate::settings::count(
372                config,
373                "output.most_frequent_shown",
374            )?),
375        })
376    }
377
378    /// Refuses ordering or de-duplicating by a field the projection removed.
379    ///
380    /// FR-036 states both halves of this and they are not the same case. A
381    /// field absent from SOME ROWS is a fact about the data, discovered by
382    /// reading it, and those rows sort to the end: tolerating that is right,
383    /// because the caller could not have known. A field absent from the
384    /// PROJECTION is a fact about the call, known before anything is sent, and
385    /// it is the caller contradicting themselves — they asked for the field to
386    /// be dropped and for the answer to be arranged by it.
387    ///
388    /// Tolerating the second was measured doing real harm. `--select key
389    /// --sort origin` ended in 0 and moved the first row from `conn.default` to
390    /// `conn.default_port`: an order the caller did not ask for, in an answer
391    /// that no longer carries the field that produced it, with nothing anywhere
392    /// saying so. A caller who mistypes the field gets the same silence.
393    ///
394    /// Refusing costs the caller one message and refusing early costs no
395    /// connection, which is the same trade every other gate in this product
396    /// makes when the call contradicts itself.
397    ///
398    /// # Errors
399    ///
400    /// Returns a usage failure naming the field and the fields still present.
401    /// A cell ceiling of zero is refused rather than quietly ignored.
402    ///
403    /// # Why this is here and not only on the stored key
404    ///
405    /// `output.truncate_cell` publishes its domain as a whole number above
406    /// zero, and the stored value is checked against it. The flag of the same
407    /// name was not, so `--truncate-cell 0` was accepted and did nothing: the
408    /// caller asked for every cell to be cut to nothing, the product answered
409    /// with whole cells, and said 0.
410    ///
411    /// A flag accepted and ignored is worse than one refused, because the
412    /// caller believes they asked. FR-038 publishes the refusal, and it now
413    /// exists on both halves of the same setting rather than one.
414    ///
415    /// # Errors
416    ///
417    /// Returns a usage failure naming the value and the domain it left.
418    fn refuses_a_cell_ceiling_of_nothing(&self) -> crate::error::Result<()> {
419        if self.output.truncate_cell != Some(0) {
420            return Ok(());
421        }
422        Err(crate::error::Failure::usage(
423            "usage.cell_ceiling_of_nothing",
424            "`--truncate-cell 0` asks for cells cut to nothing",
425        )
426        .with_detail("domain", "a whole number above zero")
427        .with_hint("write a ceiling above zero, or leave the flag out to keep whole cells"))
428    }
429
430    fn refuses_ordering_by_a_field_it_removed(&self) -> crate::error::Result<()> {
431        if self.output.select.is_empty() {
432            return Ok(());
433        }
434        // Compared as the projection compares them, so a caller is never
435        // refused for a difference the projection itself would have ignored.
436        let kept = |field: &str| {
437            self.output
438                .select
439                .iter()
440                .any(|name| name.trim() == field.trim())
441        };
442
443        for (flag, asked) in [
444            ("--sort", self.output.sort.as_deref()),
445            ("--dedupe-by", self.output.dedupe_by.as_deref()),
446        ] {
447            let Some(field) = asked else { continue };
448            if kept(field) {
449                continue;
450            }
451            return Err(crate::error::Failure::usage(
452                "usage.field_not_in_projection",
453                format!("`{flag} {field}` names a field `--select` does not keep"),
454            )
455            .with_detail("field", field)
456            .with_detail("kept", self.output.select.join(","))
457            .with_hint("add the field to --select, or order by one it keeps"));
458        }
459        Ok(())
460    }
461
462    /// Refuses a profile of the whole set written as a continuous flow.
463    ///
464    /// FR-040 refuses this combination outright rather than quietly gathering:
465    /// a caller who asked for a flow AND for a profile of the whole set asked
466    /// for two things that cannot both hold, and silently honouring one of them
467    /// would answer a question nobody put.
468    ///
469    /// The shape is taken as the resolved one rather than read from the mark on
470    /// the command line. Reading the mark, as this once did, let a caller who
471    /// had stored a line-oriented shape ask for a profile and receive one,
472    /// while a caller who wrote the same shape on the command line was refused
473    /// — the same request answered two ways by where the shape was written.
474    ///
475    /// # Errors
476    ///
477    /// Returns a usage failure when a profile was asked for over a shape that
478    /// carries one record per line.
479    pub fn refuse_a_profile_over_a_flow(&self, shape: OutputFormat) -> crate::error::Result<()> {
480        if self.output.summary && matches!(shape, OutputFormat::Ndjson | OutputFormat::Tsv) {
481            return Err(crate::error::Failure::usage(
482                "usage.summary_with_a_flow",
483                "a profile of the whole set cannot be written as a continuous flow",
484            )
485            .with_hint("drop --summary, or ask for a shape that carries one answer"));
486        }
487        Ok(())
488    }
489}
490
491#[cfg(test)]
492mod tests {
493    use clap::Parser as _;
494
495    /// The second spelling of a flag reaches the same field as the first.
496    ///
497    /// # Why an alias is worth a proof
498    ///
499    /// An alias is one line of attribute and no code, so nothing fails when it
500    /// is dropped: the flag goes on working under its first name and the second
501    /// simply stops being accepted, which a caller meets as a usage refusal
502    /// rather than as anything a build or a lint would notice.
503    ///
504    /// The two names exist because the contract publishes one and the tooling
505    /// that reaches for this product writes the other. What must never happen
506    /// is the pair drifting into two ceilings or two projections that can
507    /// disagree, so what is asserted here is that they land in ONE field.
508    #[test]
509    fn the_second_name_of_a_flag_reaches_the_same_field_as_the_first() {
510        let by_first = crate::cli::Cli::try_parse_from([
511            "mariadb-cli",
512            "--select",
513            "a,b",
514            "--limit",
515            "7",
516            "meta",
517            "version",
518        ])
519        .expect("the published spelling parses");
520        let by_second = crate::cli::Cli::try_parse_from([
521            "mariadb-cli",
522            "--fields",
523            "a,b",
524            "-n",
525            "7",
526            "meta",
527            "version",
528        ])
529        .expect("the alias parses");
530
531        assert_eq!(
532            by_first.globals.output.select, by_second.globals.output.select,
533            "`--fields` has to reach the field `--select` reaches"
534        );
535        assert_eq!(
536            by_first.globals.output.limit, by_second.globals.output.limit,
537            "`-n` has to reach the field `--limit` reaches"
538        );
539        assert_eq!(by_second.globals.output.limit, Some(7));
540    }
541
542    /// Confirming under the other name confirms, and opens nothing else.
543    ///
544    /// # The misreading this refuses
545    ///
546    /// In other tools `--force` means "past the guard", and a caller carrying
547    /// that habit would expect it to override a refusal. Here it settles one
548    /// question only — that the caller meant the change — so the second half of
549    /// this proof is the half that matters: the invocation that refuses every
550    /// change goes on refusing with the flag present.
551    #[test]
552    fn confirming_under_the_other_name_confirms_and_overrides_nothing() {
553        let by_first = crate::cli::Cli::try_parse_from(["mariadb-cli", "--yes", "meta", "version"])
554            .expect("the published spelling parses");
555        let by_second =
556            crate::cli::Cli::try_parse_from(["mariadb-cli", "--force", "meta", "version"])
557                .expect("the alias parses");
558        assert_eq!(by_first.globals.safety.yes, by_second.globals.safety.yes);
559        assert!(by_second.globals.safety.yes);
560
561        // The guard it must not open. Read-only is answered before confirmation
562        // is ever consulted, so the two cannot trade places.
563        let forced = crate::cli::Cli::try_parse_from([
564            "mariadb-cli",
565            "--force",
566            "--read-only",
567            "meta",
568            "version",
569        ])
570        .expect("both flags parse together");
571        assert!(
572            forced.globals.safety.read_only,
573            "confirming must not clear the refusal of every change"
574        );
575    }
576}