firestore-cli 0.3.0

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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
use crate::render::counted;
use crate::script::Input;
use firestore::errors::FirestoreError;
use firestore::gcloud_sdk::tonic::Code;
use firestore::{FirestoreCollectionId, FirestoreInstant};
use std::fmt::{Display, Formatter};
use std::num::{NonZeroUsize, ParseFloatError, ParseIntError};
use std::path::{Path, PathBuf};
use std::str::{FromStr, ParseBoolError};
use thiserror::Error;

pub type FsqResult<T> = Result<T, FsqError>;

/// Whether `error` is Firestore refusing a call with `FAILED_PRECONDITION`: a Standard edition
/// database refuses a pipeline so, and any database a write whose update time precondition does
/// not hold, because the document changed since it was read or no longer exists.
pub fn is_failed_precondition(error: &FirestoreError) -> bool {
    matches!(
        error,
        FirestoreError::DatabaseError(refused)
            if refused.public.code == format!("{:?}", Code::FailedPrecondition)
    )
}

/// Whether `error` is Firestore refusing a write that needs the document missing, because it
/// exists. The firestore crate reports `ALREADY_EXISTS` as a data conflict.
pub fn is_existing_document(error: &FirestoreError) -> bool {
    matches!(
        error,
        FirestoreError::DataConflictError(conflict)
            if conflict.public.code == format!("{:?}", Code::AlreadyExists)
    )
}

#[derive(Debug, Error)]
pub enum FsqError {
    #[error(transparent)]
    Firestore(#[from] FirestoreError),
    #[error("no project: pass -p or set GOOGLE_CLOUD_PROJECT")]
    NoProject,
    #[error(transparent)]
    InvalidCollectionPath(InvalidCollectionPath),
    #[error(transparent)]
    InvalidSampleSize(InvalidSampleSize),
    #[error(transparent)]
    InvalidTreeDepth(InvalidTreeDepth),
    #[error(transparent)]
    UnknownMetaCommand(UnknownMetaCommand),
    #[error(transparent)]
    InvalidMetaArgument(InvalidMetaArgument),
    #[error(transparent)]
    MissingMetaArgument(MissingMetaArgument),
    #[error(transparent)]
    UnclosedQuote(UnclosedQuote),
    #[error("{}", .0.to_string().trim().trim_start_matches("error: "))]
    MetaArguments(#[from] clap::Error),
    #[error(transparent)]
    InvalidParameter(InvalidParameter),
    #[error("no SELECT has run yet: give \\gen one")]
    NoSelectToGenerate,
    #[error("no rows have been shown yet, so there is no row to show")]
    NoRowsToShow,
    #[error(transparent)]
    RowOutOfRange(RowOutOfRange),
    #[error(transparent)]
    FileAccessFailed(FileAccessFailed),
    #[error("export needs a collection or --sql")]
    ExportWithoutSource,
    #[error("export --sql runs a SELECT, and this statement is not one")]
    ExportNeedsRows,
    #[error(transparent)]
    ImportLine(ImportLine),
    #[error(transparent)]
    ImportWrite(ImportWrite),
    #[error(transparent)]
    ImportBatchRefused(ImportBatchRefused),
    #[error(transparent)]
    Json(#[from] serde_json::Error),
    #[error(transparent)]
    InvalidIndexesFile(InvalidIndexesFile),
    #[error(transparent)]
    InvalidIndexField(InvalidIndexField),
    #[error(transparent)]
    PagerFailed(PagerFailed),
    #[error("interrupted")]
    Interrupted,
    #[error("browse draws on the terminal, and stdin or stdout is not one")]
    BrowseNeedsTerminal,
    #[error("a call to Firestore failed: {0}")]
    CallPanicked(#[source] tokio::task::JoinError),
    #[error(transparent)]
    NoUpdateTime(NoUpdateTime),
    #[error(transparent)]
    DeleteRefused(DeleteRefused),
    #[error(transparent)]
    InvalidValueText(InvalidValueText),
    #[error(transparent)]
    InvalidEditedText(InvalidEditedText),
    #[error(transparent)]
    InvalidFieldName(InvalidFieldName),
    #[error(transparent)]
    EditorFailed(EditorFailed),
    #[error(transparent)]
    InputsFailed(InputsFailed),
    #[error(transparent)]
    ScriptInputFailed(ScriptInputFailed),
    #[error(transparent)]
    Readline(#[from] reedline::ReedlineError),
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

#[derive(Debug, Error)]
#[error("`{path}` is not a collection path: {reason}")]
pub struct InvalidCollectionPath {
    pub path: String,
    pub reason: &'static str,
}

#[derive(Debug, Error)]
#[error("`{value}` is not a sample size: {source}")]
pub struct InvalidSampleSize {
    pub value: String,
    #[source]
    pub source: ParseIntError,
}

#[derive(Debug, Error)]
#[error("`{value}` is not a depth: {source}")]
pub struct InvalidTreeDepth {
    pub value: String,
    #[source]
    pub source: ParseIntError,
}

#[derive(Debug, Error)]
#[error("unknown command `{command}`, \\? lists the commands")]
pub struct UnknownMetaCommand {
    pub command: String,
}

#[derive(Debug, Error)]
#[error("{command} takes {expected}, not `{argument}`")]
pub struct InvalidMetaArgument {
    pub command: &'static str,
    pub argument: String,
    pub expected: &'static str,
}

#[derive(Debug, Error)]
#[error("row {row} is out of range: the last result has {}", counted(*.rows, "row", "rows"))]
pub struct RowOutOfRange {
    pub row: NonZeroUsize,
    pub rows: usize,
}

#[derive(Debug, Error)]
#[error("{command} needs {expected}")]
pub struct MissingMetaArgument {
    pub command: &'static str,
    pub expected: &'static str,
}

#[derive(Debug, Error)]
#[error("{command} was given a quote that is never closed: {arguments}")]
pub struct UnclosedQuote {
    pub command: &'static str,
    pub arguments: String,
}

#[derive(Debug, Error)]
#[error("`{argument}` is not a parameter: {problem}")]
pub struct InvalidParameter {
    pub argument: String,
    #[source]
    pub problem: ParameterProblem,
}

/// What is wrong with a `--param`.
#[derive(Debug, Error)]
pub enum ParameterProblem {
    #[error("write it as name=value")]
    MissingValue,
    #[error("the name is empty")]
    EmptyName,
    #[error("the value is not a JSON literal, and a string needs its quotes: {0}")]
    NotJson(#[source] serde_json::Error),
}

#[derive(Debug, Error)]
#[error("cannot {access} {}: {source}", path.display())]
pub struct FileAccessFailed {
    pub path: PathBuf,
    pub access: FileAccess,
    #[source]
    pub source: std::io::Error,
}

/// What fsq wanted a file for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileAccess {
    Read,
    Write,
}

impl Display for FileAccess {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Read => "read",
            Self::Write => "write",
        })
    }
}

/// A line of an import file that is not a document.
#[derive(Debug, Error)]
#[error("line {line}: {cause}")]
pub struct ImportLine {
    pub line: usize,
    #[source]
    pub cause: ImportLineCause,
}

#[derive(Debug, Error)]
pub enum ImportLineCause {
    #[error("not JSON: {0}")]
    InvalidJson(#[source] serde_json::Error),
    #[error(transparent)]
    Firestore(#[from] FirestoreError),
}

/// A document of an import file that Firestore refused to write.
#[derive(Debug, Error)]
#[error("line {line}: writing {document} failed with {code:?}: {message}")]
pub struct ImportWrite {
    pub line: usize,
    pub document: String,
    pub code: Code,
    pub message: String,
}

/// A request that Firestore refused as a whole, so that none of the documents of its lines was
/// written.
#[derive(Debug, Error)]
#[error("lines {first_line} to {last_line}: the request was refused: {cause}")]
pub struct ImportBatchRefused {
    pub first_line: usize,
    pub last_line: usize,
    #[source]
    pub cause: FirestoreError,
}

#[derive(Debug, Error)]
#[error("{} is not an indexes file: {source}", path.display())]
pub struct InvalidIndexesFile {
    pub path: PathBuf,
    #[source]
    pub source: IndexesFileProblem,
}

/// What is wrong with the text of an indexes file.
#[derive(Debug, Error)]
pub enum IndexesFileProblem {
    #[error(transparent)]
    Json(#[from] serde_json::Error),
    #[error(transparent)]
    FieldMode(InvalidFieldMode),
    #[error(transparent)]
    UnsupportedSetting(UnsupportedSetting),
}

/// A Firebase index setting that the firestore crate has no model for.
#[derive(Debug, Error)]
#[error("the index of `{collection_group}` sets {setting}, which fsq cannot declare")]
pub struct UnsupportedSetting {
    pub collection_group: FirestoreCollectionId,
    pub setting: &'static str,
}

#[derive(Debug, Error)]
#[error("the field `{field_path}` must set exactly one of order, arrayConfig, searchConfig and vectorConfig")]
pub struct InvalidFieldMode {
    pub field_path: String,
}

#[derive(Debug, Error)]
#[error(
    "`{value}` is not an index field: write it as <field>:asc, <field>:desc or <field>:contains"
)]
pub struct InvalidIndexField {
    pub value: String,
}

#[derive(Debug, Error)]
#[error("the pager `{command}` failed: {source}")]
pub struct PagerFailed {
    pub command: String,
    #[source]
    pub source: std::io::Error,
}

/// A document read without its update time, which the precondition of a write to it needs.
#[derive(Debug, Error)]
#[error("{document} was read without its update time, so a write cannot check that it is unchanged; r reads the documents again")]
pub struct NoUpdateTime {
    pub document: String,
}

/// A document of a recursive delete that Firestore refused to delete.
#[derive(Debug, Error)]
#[error("deleting {document} failed with {code:?}: {message}")]
pub struct DeleteRefused {
    pub document: String,
    pub code: Code,
    pub message: String,
}

/// A text in the browser's value editor that does not read as a value of the type of its field.
#[derive(Debug, Error)]
#[error("`{text}` is not {problem}")]
pub struct InvalidValueText {
    pub text: String,
    #[source]
    pub problem: ValueTextProblem,
}

/// What a text is not, by the type it was read as, and why.
#[derive(Debug, Error)]
pub enum ValueTextProblem {
    #[error("an integer: {0}")]
    Integer(#[source] ParseIntError),
    #[error("a double: {0}")]
    Double(#[source] ParseFloatError),
    #[error("a boolean: {0}")]
    Boolean(#[source] ParseBoolError),
    #[error("an RFC 3339 timestamp: {0}")]
    Timestamp(#[source] <FirestoreInstant as FromStr>::Err),
    #[error("a geopoint: {0}")]
    GeoPoint(#[source] GeoPointProblem),
}

/// Why a text is not a geopoint.
#[derive(Debug, Error)]
pub enum GeoPointProblem {
    #[error("write it as (latitude, longitude)")]
    NotAPair,
    #[error("a coordinate is not a number: {0}")]
    Coordinate(#[source] ParseFloatError),
}

/// A text the external editor saved that the browser does not write.
#[derive(Debug, Error)]
pub enum InvalidEditedText {
    #[error("not JSON: {0}")]
    NotJson(#[source] serde_json::Error),
    #[error("not a value in the tagged encoding: {0}")]
    NotTagged(#[source] FirestoreError),
    #[error(transparent)]
    NotHexDump(#[from] InvalidHexDump),
    #[error("`__name__` is {edited}, not {read}: an edit keeps the ID, and D copies a document under a new one")]
    Renamed { read: String, edited: String },
    #[error("`__name__` is {edited}, not {collection}/ and an ID: a new document goes in the collection on show, and {collection}/ alone gives it a new ID")]
    OutsideCollection { collection: String, edited: String },
}

/// A name the browser does not give a field it adds.
#[derive(Debug, Error)]
pub enum InvalidFieldName {
    #[error("a field needs a name")]
    Empty,
    #[error("`{field}` exists already")]
    Taken { field: String },
}

/// A line of a hex dump that does not read as bytes.
#[derive(Debug, Error)]
#[error("line {line}: {problem}")]
pub struct InvalidHexDump {
    pub line: usize,
    #[source]
    pub problem: HexDumpProblem,
}

#[derive(Debug, Error)]
pub enum HexDumpProblem {
    #[error("`{0}` is not a hexadecimal digit")]
    NotHexDigit(char),
    #[error("the line has an odd number of hexadecimal digits, and a byte is two")]
    OddDigits,
}

#[derive(Debug, Error)]
#[error("the editor `{program}` did not run: {source}")]
pub struct EditorFailed {
    pub program: String,
    #[source]
    pub source: std::io::Error,
}

#[derive(Debug, Error)]
#[error("{failed} of the inputs failed")]
pub struct InputsFailed {
    pub failed: usize,
}

/// An input of a script, which stops at the first failure, with the position and start of the
/// input that failed.
#[derive(Debug, Error)]
#[error("input {number} ({excerpt}) failed: {source}")]
pub struct ScriptInputFailed {
    pub number: usize,
    pub excerpt: String,
    #[source]
    pub source: Box<FsqError>,
}

impl FsqError {
    /// This error as the failure of input `number` of a script. An interrupt and a closed output
    /// pipe are not failures of the input, and the caller's exit code depends on seeing them as
    /// they are.
    pub fn in_input(self, number: usize, input: &Input) -> Self {
        if matches!(self, Self::Interrupted) || self.is_broken_pipe() {
            return self;
        }
        Self::ScriptInputFailed(ScriptInputFailed {
            number,
            excerpt: input.excerpt(),
            source: Box::new(self),
        })
    }

    pub fn file_access(path: &Path, access: FileAccess, source: std::io::Error) -> Self {
        Self::FileAccessFailed(FileAccessFailed {
            path: path.to_path_buf(),
            access,
            source,
        })
    }

    pub fn invalid_meta_argument(
        command: &'static str,
        argument: &str,
        expected: &'static str,
    ) -> Self {
        Self::InvalidMetaArgument(InvalidMetaArgument {
            command,
            argument: argument.to_string(),
            expected,
        })
    }

    pub fn missing_meta_argument(command: &'static str, expected: &'static str) -> Self {
        Self::MissingMetaArgument(MissingMetaArgument { command, expected })
    }

    /// The reader of piped output, such as `head`, stopped reading.
    pub fn is_broken_pipe(&self) -> bool {
        matches!(self, Self::Io(error) if error.kind() == std::io::ErrorKind::BrokenPipe)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_failure_is_named_by_its_input_and_an_interrupt_or_a_closed_pipe_is_not() {
        let input = Input::Statement("SELECT 1".to_string());
        let closed_pipe = FsqError::Io(std::io::ErrorKind::BrokenPipe.into());

        assert!(matches!(
            FsqError::NoProject.in_input(2, &input),
            FsqError::ScriptInputFailed(ScriptInputFailed { number: 2, ref source, .. })
                if matches!(**source, FsqError::NoProject)
        ));
        assert!(matches!(
            FsqError::Interrupted.in_input(2, &input),
            FsqError::Interrupted
        ));
        assert!(closed_pipe.in_input(2, &input).is_broken_pipe());
    }
}