firestore-cli 0.1.1

fsq, a command line client for Google Firestore: a SQL REPL with tables, query plans and index statements, and a scripting mode with JSON output
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
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,
    /// `\l`, or with `--recursive` a walk of the collections below the root.
    ListCollections(Option<CollectionTreeTarget>),
    Describe(DescribeTarget),
    /// `\x` without an argument toggles between the table and the expanded view.
    Expanded(Option<ExpandedMode>),
    /// `\x full N`: row `N` of the last result in the expanded view, counting from 1.
    ExpandedRow(NonZeroUsize),
    Connect(DatabaseId),
    /// Without an argument, toggles.
    Timing(Option<Switch>),
    /// Without an argument, toggles.
    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",
        })
    }
}

/// A meta-command as the help lists it and the REPL completes it.
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: "\\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";

/// The text of `\?`: a table of the meta-commands and what they do, and a note on quoting. In a
/// terminal of `width` columns the cells wrap at their spaces to fit it.
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)?),
            "\\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)
    }
}

/// The arguments of `\l`: the options of a recursive listing only make sense with `--recursive`.
#[derive(Args)]
struct ListCollections {
    #[arg(long)]
    recursive: bool,

    #[command(flatten)]
    target: CollectionTreeTarget,
}

/// Reads the arguments of a meta-command as clap reads those of a command, after the quoting of
/// a shell has split them into words.
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 {
    /// The switch a `\timing` or `\wait` argument names, in any case.
    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::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 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(_))
            ));
        }
    }
}