use crate::browse::BrowseTarget;
use crate::codegen::GenerateCommand;
use crate::collection_tree::CollectionTreeTarget;
use crate::connection::DatabaseId;
use crate::describe::DescribeTarget;
use crate::errors::{FsqError, FsqResult, UnclosedQuote, UnknownMetaCommand};
use crate::render::{ExpandedMode, TableText, Theme};
use clap::{Args, Command, FromArgMatches};
use std::num::NonZeroUsize;
use std::str::FromStr;
#[derive(Debug, Clone, PartialEq)]
pub enum MetaCommand {
Quit,
Help,
ListCollections(Option<CollectionTreeTarget>),
Describe(DescribeTarget),
Browse(BrowseTarget),
Expanded(Option<ExpandedMode>),
ExpandedRow(NonZeroUsize),
Connect(DatabaseId),
Timing(Option<Switch>),
Wait(Option<Switch>),
Generate(GenerateCommand),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Switch {
On,
Off,
}
impl Switch {
pub fn toggled(self) -> Self {
match self {
Self::On => Self::Off,
Self::Off => Self::On,
}
}
}
impl std::fmt::Display for Switch {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::On => "on",
Self::Off => "off",
})
}
}
pub struct MetaCommandHelp {
pub usage: &'static str,
pub summary: &'static str,
}
impl MetaCommandHelp {
pub fn name(&self) -> &'static str {
self.usage
.split_once(' ')
.map_or(self.usage, |(name, _)| name)
}
}
pub const META_COMMANDS: &[MetaCommandHelp] = &[
MetaCommandHelp {
usage: "\\l [--recursive [--depth N] [--sample K]]",
summary: "list the collections under the root; --recursive samples K documents (20) per collection, down to depth N (2)",
},
MetaCommandHelp {
usage: "\\d <collection> [--sample N]",
summary: "list a collection's field paths, types, % present and an example",
},
MetaCommandHelp {
usage: "\\browse <collection> [filter]",
summary: "browse a collection full screen, opening maps, arrays and subcollections; the filter is the end of a SELECT, such as WHERE genre = 'sf' LIMIT 20, and without a LIMIT the first 100 documents show",
},
MetaCommandHelp {
usage: "\\x [on|off|auto|full [N]]",
summary: "expanded view, one block per document; auto when a table is too wide; full shows every field with its type and whole value, and full N shows row N of the last result",
},
MetaCommandHelp {
usage: "\\c <database>",
summary: "connect to another database of the project",
},
MetaCommandHelp {
usage: "\\timing [on|off]",
summary: "round trip time and execution stats in the footer",
},
MetaCommandHelp {
usage: "\\wait [on|off]",
summary: "wait for CREATE INDEX and ALTER COLLECTION to finish",
},
MetaCommandHelp {
usage: "\\gen ['SELECT'] [--param NAME=VALUE] [--sample N] [--offline]",
summary: "fluent Rust code of a SELECT, or of the last one run",
},
MetaCommandHelp {
usage: "\\?",
summary: "this help",
},
MetaCommandHelp {
usage: "\\q",
summary: "quit",
},
];
const QUOTING_NOTE: &str = "The arguments of \\l, \\d and \\gen are split as a shell splits them:\nquote the SELECT, and a value that holds spaces or quotes, as in\n \\gen 'SELECT title FROM books WHERE genre = @genre' --param 'genre=\"science fiction\"'\n";
pub fn meta_help(theme: &Theme, width: Option<usize>) -> String {
let cells = TableText::new(
["command", "description"]
.map(|header| theme.header.apply_to(header).to_string())
.to_vec(),
META_COMMANDS
.iter()
.map(|command| vec![command.usage.to_string(), command.summary.to_string()])
.collect(),
);
let table = match width {
Some(width) => cells.into_wrapped_table(width),
None => cells.into_table(),
};
format!("{table}\n\n{QUOTING_NOTE}")
}
impl FromStr for MetaCommand {
type Err = FsqError;
fn from_str(line: &str) -> FsqResult<Self> {
let line = line.trim_start();
let (command, rest) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
let command = match command {
"\\q" => no_arguments("\\q", rest, Self::Quit)?,
"\\quit" => no_arguments("\\quit", rest, Self::Quit)?,
"\\?" => no_arguments("\\?", rest, Self::Help)?,
"\\l" => {
let ListCollections { recursive, target } = parse_arguments("\\l", rest)?;
Self::ListCollections(recursive.then_some(target))
}
"\\d" => Self::Describe(parse_arguments("\\d", rest)?),
"\\browse" => {
let rest = rest.trim();
let (collection, filter) =
rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
if collection.is_empty() {
return Err(FsqError::missing_meta_argument(
"\\browse",
"a collection path",
));
}
if let Some(flag) = filter.strip_prefix("--filter") {
if flag.is_empty() || flag.starts_with(|c: char| c.is_whitespace() || c == '=')
{
return Err(FsqError::invalid_meta_argument(
"\\browse",
"--filter",
"the filter as the rest of the line, without a flag",
));
}
}
Self::Browse(BrowseTarget {
collection: collection.parse()?,
filter: filter.into(),
})
}
"\\x" => match rest.split_whitespace().collect::<Vec<_>>().as_slice() {
[full, row] if full.eq_ignore_ascii_case("full") => {
Self::ExpandedRow(row.parse().map_err(|_| {
FsqError::invalid_meta_argument("\\x", row, "a row number, counting from 1")
})?)
}
_ => Self::Expanded(optional_argument(
"\\x",
rest,
"on, off, auto or full",
ExpandedMode::from_argument,
)?),
},
"\\c" => match rest.split_whitespace().collect::<Vec<_>>().as_slice() {
[database] => Self::Connect(DatabaseId::from(*database)),
[] => return Err(FsqError::missing_meta_argument("\\c", "a database ID")),
[_, extra, ..] => {
return Err(FsqError::invalid_meta_argument(
"\\c",
extra,
"one database ID",
))
}
},
"\\timing" => Self::Timing(optional_argument(
"\\timing",
rest,
"on or off",
Switch::from_argument,
)?),
"\\wait" => Self::Wait(optional_argument(
"\\wait",
rest,
"on or off",
Switch::from_argument,
)?),
"\\gen" => Self::Generate(parse_arguments("\\gen", rest)?),
other => {
return Err(FsqError::UnknownMetaCommand(UnknownMetaCommand {
command: other.to_string(),
}))
}
};
Ok(command)
}
}
#[derive(Args)]
struct ListCollections {
#[arg(long)]
recursive: bool,
#[command(flatten)]
target: CollectionTreeTarget,
}
fn parse_arguments<A: Args + FromArgMatches>(
command: &'static str,
arguments: &str,
) -> FsqResult<A> {
let words = shlex::split(arguments).ok_or_else(|| {
FsqError::UnclosedQuote(UnclosedQuote {
command,
arguments: arguments.to_string(),
})
})?;
let matches = A::augment_args(
Command::new(command)
.no_binary_name(true)
.disable_help_flag(true),
)
.try_get_matches_from(words)?;
Ok(A::from_arg_matches(&matches)?)
}
impl Switch {
fn from_argument(argument: &str) -> Option<Self> {
match argument.to_ascii_lowercase().as_str() {
"on" => Some(Self::On),
"off" => Some(Self::Off),
_ => None,
}
}
}
fn no_arguments(command: &'static str, rest: &str, parsed: MetaCommand) -> FsqResult<MetaCommand> {
match rest.split_whitespace().next() {
None => Ok(parsed),
Some(argument) => Err(FsqError::invalid_meta_argument(
command,
argument,
"no arguments",
)),
}
}
fn optional_argument<T>(
command: &'static str,
rest: &str,
expected: &'static str,
from_argument: fn(&str) -> Option<T>,
) -> FsqResult<Option<T>> {
match rest.split_whitespace().collect::<Vec<_>>().as_slice() {
[] => Ok(None),
[argument] => from_argument(argument)
.map(Some)
.ok_or_else(|| FsqError::invalid_meta_argument(command, argument, expected)),
[_, extra, ..] => Err(FsqError::invalid_meta_argument(command, extra, expected)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::browse::FilterTail;
use crate::codegen::tests::binding;
use crate::describe::SampleSize;
use crate::errors::{InvalidMetaArgument, MissingMetaArgument};
fn parsed(line: &str) -> MetaCommand {
line.parse().expect(line)
}
#[test]
fn the_help_fits_the_terminal_without_cutting_any_text() {
for width in [80, 120] {
let help = meta_help(&Theme::new(false), Some(width));
let table: Vec<_> = help.lines().take_while(|line| !line.is_empty()).collect();
assert!(table.iter().all(|line| line.chars().count() <= width));
assert!(!help.contains('…'));
for command in META_COMMANDS {
for word in command.summary.split_whitespace() {
assert!(help.contains(word), "{width}: `{word}` is missing");
}
}
}
}
#[test]
fn meta_commands_parse_with_their_arguments() {
assert_eq!(parsed("\\q"), MetaCommand::Quit);
assert_eq!(parsed("\\l"), MetaCommand::ListCollections(None));
assert_eq!(parsed("\\x"), MetaCommand::Expanded(None));
assert_eq!(
parsed("\\x auto"),
MetaCommand::Expanded(Some(ExpandedMode::Auto))
);
assert_eq!(
parsed("\\x FULL"),
MetaCommand::Expanded(Some(ExpandedMode::Full))
);
assert_eq!(parsed("\\timing on"), MetaCommand::Timing(Some(Switch::On)));
assert_eq!(parsed("\\wait OFF"), MetaCommand::Wait(Some(Switch::Off)));
assert_eq!(
parsed("\\c firestore-rs-enterprise"),
MetaCommand::Connect(DatabaseId::from("firestore-rs-enterprise"))
);
assert_eq!(
parsed("\\d users/alice/orders --sample 20"),
MetaCommand::Describe(DescribeTarget {
collection: "users/alice/orders".parse().expect("a collection path"),
sample: "20".parse().expect("a sample size"),
})
);
assert_eq!(
parsed("\\d books"),
MetaCommand::Describe(DescribeTarget {
collection: "books".parse().expect("a collection path"),
sample: SampleSize::default(),
})
);
}
fn generated(line: &str) -> GenerateCommand {
match parsed(line) {
MetaCommand::Generate(command) => command,
other => panic!("{other:?}"),
}
}
#[test]
fn an_option_inside_a_string_of_the_select_belongs_to_the_select() {
let command =
generated(r#"\gen "SELECT title FROM books WHERE note = 'see --param x'" --param a=1"#);
assert_eq!(
command.sql.as_deref(),
Some("SELECT title FROM books WHERE note = 'see --param x'")
);
assert_eq!(command.options.parameters, vec![binding("a=1")]);
}
#[test]
fn an_option_inside_a_comment_of_the_select_belongs_to_the_select() {
let command = generated("\\gen 'SELECT title FROM books -- --sample 5'");
assert_eq!(
command.sql.as_deref(),
Some("SELECT title FROM books -- --sample 5")
);
assert!(command.options.parameters.is_empty());
assert_eq!(
command.options.sample_rows(),
Some(SampleSize::CODEGEN_DEFAULT)
);
}
#[test]
fn gen_without_a_select_leaves_it_to_the_last_one_that_ran() {
assert_eq!(generated("\\gen").sql, None);
assert_eq!(generated("\\gen --offline").options.sample_rows(), None);
}
#[test]
fn a_json_parameter_with_a_space_is_quoted_like_a_shell_argument() {
let command = generated(r#"\gen 'SELECT 1' --param 'genre="science fiction"'"#);
assert_eq!(
command.options.parameters,
vec![binding("genre=\"science fiction\"")]
);
}
#[test]
fn a_quote_that_is_never_closed_is_refused() {
assert!(matches!(
"\\gen 'SELECT 1".parse::<MetaCommand>(),
Err(FsqError::UnclosedQuote(_))
));
}
#[test]
fn a_wrong_argument_names_the_command_and_the_argument() {
match "\\x sideways".parse::<MetaCommand>() {
Err(FsqError::InvalidMetaArgument(InvalidMetaArgument {
command, argument, ..
})) => {
assert_eq!(command, "\\x");
assert_eq!(argument, "sideways");
}
other => panic!("{other:?}"),
}
assert!(matches!(
"\\c".parse::<MetaCommand>(),
Err(FsqError::MissingMetaArgument(MissingMetaArgument {
command: "\\c",
..
}))
));
assert!(matches!(
"\\frobnicate".parse::<MetaCommand>(),
Err(FsqError::UnknownMetaCommand(UnknownMetaCommand { command })) if command == "\\frobnicate"
));
}
#[test]
fn browse_keeps_the_rest_of_the_line_as_the_filter_quotes_and_all() {
assert_eq!(
parsed("\\browse users/alice/orders WHERE genre = 'sf' LIMIT 5 "),
MetaCommand::Browse(BrowseTarget {
collection: "users/alice/orders".parse().expect("a collection path"),
filter: "WHERE genre = 'sf' LIMIT 5".into(),
})
);
assert_eq!(
parsed("\\browse books"),
MetaCommand::Browse(BrowseTarget {
collection: "books".parse().expect("a collection path"),
filter: FilterTail::default(),
})
);
}
#[test]
fn browse_refuses_the_filter_flag_of_the_command_line() {
for line in [
"\\browse books --filter \"WHERE pages > 100\"",
"\\browse books --filter=\"WHERE pages > 100\"",
] {
assert!(
matches!(
line.parse::<MetaCommand>(),
Err(FsqError::InvalidMetaArgument(InvalidMetaArgument {
command: "\\browse",
..
}))
),
"{line}"
);
}
}
#[test]
fn browse_without_a_collection_names_what_it_needs() {
assert!(matches!(
"\\browse ".parse::<MetaCommand>(),
Err(FsqError::MissingMetaArgument(MissingMetaArgument {
command: "\\browse",
..
}))
));
}
#[test]
fn x_full_with_a_row_number_shows_that_row() {
assert_eq!(
parsed("\\x full 12"),
MetaCommand::ExpandedRow(NonZeroUsize::new(12).expect("non-zero"))
);
}
#[test]
fn x_full_takes_a_row_counted_from_one() {
for argument in ["0", "-1", "two", "1 2"] {
match format!("\\x full {argument}").parse::<MetaCommand>() {
Err(FsqError::InvalidMetaArgument(InvalidMetaArgument { command, .. })) => {
assert_eq!(command, "\\x")
}
other => panic!("{argument}: {other:?}"),
}
}
}
#[test]
fn quit_names_itself_in_its_error() {
for command in ["\\q", "\\quit"] {
match format!("{command} now").parse::<MetaCommand>() {
Err(FsqError::InvalidMetaArgument(InvalidMetaArgument {
command: named, ..
})) => assert_eq!(named, command),
other => panic!("{other:?}"),
}
}
}
#[test]
fn every_listed_command_is_one_the_parser_knows() {
for command in META_COMMANDS {
assert!(!matches!(
command.name().parse::<MetaCommand>(),
Err(FsqError::UnknownMetaCommand(_))
));
}
}
}