use clap::{Args, ValueEnum};
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "lower")]
pub enum OutputFormat {
Json,
Ndjson,
Tsv,
Text,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "lower")]
pub enum RowCountMode {
Matched,
Changed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "lower")]
pub enum Compress {
Auto,
Always,
Never,
}
#[derive(Debug, Clone, Args)]
pub struct DestinationFlags {
#[arg(long, global = true, value_name = "NAME")]
pub profile: Option<String>,
#[arg(long, global = true, value_name = "NAME")]
pub database: Option<String>,
#[arg(long, global = true, value_name = "TEXT", conflicts_with = "profile")]
pub dsn: Option<String>,
#[arg(long, global = true, conflicts_with_all = ["profile", "dsn"])]
pub all_profiles: bool,
}
impl DestinationFlags {
#[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 {
crate::output::envelope::TargetSource::Selector
} else {
crate::output::envelope::TargetSource::Config
}
}
}
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Args)]
pub struct OutputFlags {
#[arg(long, global = true, value_enum, value_name = "FORMAT")]
pub output_format: Option<OutputFormat>,
#[arg(long, global = true)]
pub print_schema: bool,
#[arg(
long,
visible_alias = "fields",
global = true,
value_name = "FIELDS",
value_delimiter = ','
)]
pub select: Vec<String>,
#[arg(long, global = true, value_name = "EXPR")]
pub filter: Vec<String>,
#[arg(long, global = true, value_name = "FIELD")]
pub sort: Option<String>,
#[arg(long, global = true, value_name = "FIELD")]
pub dedupe_by: Option<String>,
#[arg(long, global = true)]
pub count_only: bool,
#[arg(short = 'n', long, global = true, value_name = "N")]
pub limit: Option<usize>,
#[arg(long, global = true, value_name = "MARK")]
pub cursor: Option<String>,
#[arg(long, global = true)]
pub redact: bool,
#[arg(long, global = true, value_name = "N")]
pub truncate_cell: Option<usize>,
#[arg(long, global = true, value_name = "N")]
pub max_output_bytes: Option<usize>,
#[arg(long, global = true)]
pub summary: bool,
#[arg(long, global = true, value_name = "FILE")]
pub output: Option<std::path::PathBuf>,
#[arg(long, global = true)]
pub checksum: bool,
#[arg(long, global = true, value_enum, value_name = "MODE")]
pub row_count: Option<RowCountMode>,
}
#[derive(Debug, Clone, Args)]
pub struct LimitFlags {
#[arg(long, global = true, value_name = "SECS")]
pub timeout: Option<u64>,
#[arg(long, global = true, value_name = "SECS")]
pub connect_timeout: Option<u64>,
#[arg(long, global = true, value_name = "N")]
pub retries: Option<u32>,
#[arg(long, global = true, value_name = "N")]
pub max_concurrency: Option<usize>,
#[arg(long, global = true, value_enum, value_name = "MODE")]
pub compress: Option<Compress>,
}
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Args)]
pub struct SafetyFlags {
#[arg(long, global = true)]
pub read_only: bool,
#[arg(long, short = 'y', visible_alias = "force", global = true)]
pub yes: bool,
#[arg(long, global = true)]
pub dry_run: bool,
#[arg(long, global = true, value_name = "N")]
pub max_affected: Option<u64>,
#[arg(long, global = true)]
pub no_input: bool,
#[arg(long, global = true)]
pub accept_unverified_tls: bool,
}
#[derive(Debug, Clone, Args)]
pub struct DiagnosticFlags {
#[arg(long, short = 'q', global = true, conflicts_with = "verbose")]
pub quiet: bool,
#[arg(long, short = 'v', global = true, action = clap::ArgAction::Count)]
pub verbose: u8,
#[arg(long, global = true)]
pub no_color: bool,
#[arg(long, global = true, value_name = "LANG")]
pub lang: Option<String>,
#[arg(long, global = true, value_name = "PATH")]
pub config_dir: Option<std::path::PathBuf>,
}
#[derive(Debug, Clone, Args)]
pub struct GlobalFlags {
#[command(flatten)]
pub destination: DestinationFlags,
#[command(flatten)]
pub output: OutputFlags,
#[command(flatten)]
pub limits: LimitFlags,
#[command(flatten)]
pub safety: SafetyFlags,
#[command(flatten)]
pub diagnostics: DiagnosticFlags,
}
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 {
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,
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",
)?),
})
}
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(());
}
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(())
}
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 _;
#[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));
}
#[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);
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"
);
}
}