use crate::cli::schema::{DdlArgs, SearchArgs};
use crate::error::{Failure, Result};
pub(super) fn table_of(named: Option<&String>) -> Result<String> {
named.cloned().ok_or_else(|| {
Failure::usage(
"schema.table_missing",
"this reading needs a table to read about",
)
.with_hint("name one with --table, as in `schema columns --table clientes`")
})
}
pub(super) fn pattern_of(args: &SearchArgs) -> Result<String> {
args.like
.clone()
.or_else(|| args.pattern.clone())
.ok_or_else(|| {
Failure::usage(
"schema.pattern_missing",
"the search needs a pattern to look for",
)
.with_hint("give one with --like, as in `schema search --like 'cliente%'`")
})
}
pub(super) fn object_of(args: &DdlArgs) -> Result<String> {
args.object.clone().ok_or_else(|| {
Failure::usage(
"schema.object_missing",
"writing out a definition needs the object to write out",
)
.with_hint("name one as the first word, as in `schema ddl clientes`")
})
}
pub(super) fn unknown_kind(asked: &str) -> Failure {
Failure::usage("schema.unknown_kind", format!("`{asked}`"))
.with_detail("detail", format!("`{asked}`"))
.with_detail("reason", "written")
.with_detail(
"kinds",
"table, view, procedure, function, trigger, event, sequence",
)
.with_hint("the kinds are: table, view, procedure, function, trigger, event, sequence")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_reading_without_a_table_is_refused_with_a_code() {
let failure = table_of(None).expect_err("must refuse");
assert_eq!(failure.code(), "schema.table_missing");
assert_eq!(failure.exit_number().code(), 2);
assert!(
failure.hint().is_some_and(|hint| hint.contains("--table")),
"the refusal names the flag that carries the table"
);
}
#[test]
fn a_search_without_a_pattern_is_refused_with_a_code() {
let failure = pattern_of(&SearchArgs {
pattern: None,
like: None,
kind: Vec::new(),
detail: None,
})
.expect_err("must refuse");
assert_eq!(failure.code(), "schema.pattern_missing");
assert_eq!(failure.exit_number().code(), 2);
assert!(failure.hint().is_some_and(|hint| hint.contains("--like")));
}
#[test]
fn the_pattern_may_be_written_either_way_and_the_flag_wins() {
let bare = SearchArgs {
pattern: Some("bare%".to_owned()),
like: None,
kind: Vec::new(),
detail: None,
};
assert_eq!(pattern_of(&bare).expect("a pattern"), "bare%");
let both = SearchArgs {
like: Some("flag%".to_owned()),
..bare
};
assert_eq!(pattern_of(&both).expect("a pattern"), "flag%");
}
#[test]
fn a_definition_without_an_object_is_refused_with_a_code() {
let failure = object_of(&DdlArgs {
object: None,
kind: None,
})
.expect_err("must refuse");
assert_eq!(failure.code(), "schema.object_missing");
assert_eq!(failure.exit_number().code(), 2);
assert!(failure
.hint()
.is_some_and(|hint| hint.contains("schema ddl")));
}
}