firestore-cli 0.2.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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
use super::fit::TableText;
use super::value::is_summarised;
use super::{ExpandedMode, OutputFormat, View};
use firestore::gcloud_sdk::google::firestore::v1::value::ValueType;
use firestore::gcloud_sdk::google::firestore::v1::Value;
use firestore::FirestoreDocument;
use std::collections::BTreeSet;

/// The column a document's name is shown under, as SQL selects it.
pub const NAME_COLUMN: &str = "__name__";

#[derive(Debug, Clone, PartialEq)]
pub enum Cell {
    Value(Value),
    Text(String),
    Count(u64),
    /// A share from 0 to 100: `87.5%` in a table and `87.5` in JSON.
    Percent(f64),
}

/// Rows under named columns, the one shape every tabular result is drawn from: a table, the
/// expanded view, JSON or JSON lines. A row holds `None` where it has no value for a column,
/// such as a field its document lacks.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Grid {
    columns: Vec<String>,
    rows: Vec<Vec<Option<Cell>>>,
}

impl Grid {
    pub fn new<I, S>(columns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            columns: columns.into_iter().map(Into::into).collect(),
            rows: Vec::new(),
        }
    }

    pub fn push_row(&mut self, row: Vec<Option<Cell>>) {
        debug_assert_eq!(row.len(), self.columns.len());
        self.rows.push(row);
    }

    pub fn columns(&self) -> &[String] {
        &self.columns
    }

    #[cfg(test)]
    pub fn rows(&self) -> &[Vec<Option<Cell>>] {
        &self.rows
    }

    pub fn len(&self) -> usize {
        self.rows.len()
    }

    pub fn is_empty(&self) -> bool {
        self.rows.is_empty()
    }

    fn has_summarised_value(&self) -> bool {
        self.rows
            .iter()
            .flatten()
            .flatten()
            .any(|cell| matches!(cell, Cell::Value(value) if is_summarised(value)))
    }

    /// One row per document, under the union of their fields. Firestore returns a document's
    /// fields unordered, so the columns come in `order`, the order the statement selects them in,
    /// and then by name, with the document name first when the documents have one.
    pub fn from_documents(documents: Vec<FirestoreDocument>, order: &[String]) -> Self {
        let mut fields = BTreeSet::new();
        for document in &documents {
            fields.extend(document.fields.keys().cloned());
        }
        let has_names = documents.iter().any(|document| !document.name.is_empty());
        let mut columns: Vec<String> = has_names
            .then(|| NAME_COLUMN.to_string())
            .into_iter()
            .collect();
        columns.extend(in_selected_order(fields, order));
        let rows = documents
            .into_iter()
            .map(|mut document| {
                columns
                    .iter()
                    .map(|column| match column.as_str() {
                        NAME_COLUMN if has_names => (!document.name.is_empty()).then(|| {
                            Cell::Value(Value {
                                value_type: Some(ValueType::ReferenceValue(std::mem::take(
                                    &mut document.name,
                                ))),
                            })
                        }),
                        _ => document.fields.remove(column).map(Cell::Value),
                    })
                    .collect()
            })
            .collect();
        Self { columns, rows }
    }
}

/// The field names in the order a statement selects them in, `order`, and then by name.
pub(super) fn in_selected_order(mut fields: BTreeSet<String>, order: &[String]) -> Vec<String> {
    let mut names: Vec<String> = order
        .iter()
        .filter(|name| fields.remove(*name))
        .cloned()
        .collect();
    names.extend(fields);
    names
}

impl View<'_> {
    pub fn grid(&self, grid: &Grid) -> String {
        self.grids(&[("", grid)])
    }

    /// Several grids of one statement. A table per non-empty grid, titled when several are
    /// non-empty; in JSON one array, or an object of arrays by title; in JSON lines every row.
    pub fn grids(&self, grids: &[(&str, &Grid)]) -> String {
        match self.format {
            OutputFormat::Table if grids.len() == 1 => self.grid_text(grids[0].1),
            OutputFormat::Table => {
                let shown: Vec<_> = grids.iter().filter(|(_, grid)| !grid.is_empty()).collect();
                let mut out = String::new();
                for (title, grid) in &shown {
                    if shown.len() > 1 {
                        out.push_str(&self.theme.header.apply_to(title).to_string());
                        out.push('\n');
                    }
                    out.push_str(&self.grid_text(grid));
                }
                out
            }
            OutputFormat::Json => {
                let json = match grids {
                    [(_, grid)] => self.json_rows(grid),
                    _ => serde_json::Value::Object(
                        grids
                            .iter()
                            .map(|(title, grid)| (title.to_string(), self.json_rows(grid)))
                            .collect(),
                    ),
                };
                format!("{json:#}\n")
            }
            OutputFormat::Jsonl => {
                let mut out = String::new();
                for (_, grid) in grids {
                    for row in self.json_objects(grid) {
                        out.push_str(&row.to_string());
                        out.push('\n');
                    }
                }
                out
            }
        }
    }

    /// A grid without columns, the result of a statement that returned no documents, has nothing
    /// to draw: the footer's row count is the whole answer.
    fn grid_text(&self, grid: &Grid) -> String {
        if grid.columns.is_empty() {
            return String::new();
        }
        match self.expanded {
            ExpandedMode::On => self.expanded_text(grid),
            ExpandedMode::Off | ExpandedMode::Full => {
                let mut cells = self.table_cells(grid);
                if let Some(width) = self.width {
                    cells.fit_to(width);
                }
                format!("{}\n", cells.into_table())
            }
            ExpandedMode::Auto => {
                let cells = self.table_cells(grid);
                match self.width {
                    Some(width) if cells.width() > width => self.expanded_text(grid),
                    _ => format!("{}\n", cells.into_table()),
                }
            }
        }
    }

    /// The hint that `\x full N` shows what a table of `grid` left out, or nothing when the table
    /// showed everything.
    pub fn detail_hint(&self, grid: &Grid) -> String {
        if self.format != OutputFormat::Table || !self.table_hides_detail(grid) {
            return String::new();
        }
        format!(
            "{}\n",
            self.theme
                .muted
                .apply_to("\\x full N shows every field of row N")
        )
    }

    /// Whether the table drawn for `grid` cuts a cell or summarises a value. A result drawn as
    /// records, or in the detail view, shows every value whole.
    fn table_hides_detail(&self, grid: &Grid) -> bool {
        match self.expanded {
            ExpandedMode::On | ExpandedMode::Full => false,
            ExpandedMode::Off => grid.has_summarised_value() || self.wider_than_terminal(grid),
            ExpandedMode::Auto => !self.wider_than_terminal(grid) && grid.has_summarised_value(),
        }
    }

    fn wider_than_terminal(&self, grid: &Grid) -> bool {
        self.width
            .is_some_and(|width| self.table_cells(grid).width() > width)
    }

    fn table_cells(&self, grid: &Grid) -> TableText {
        TableText::new(
            grid.columns
                .iter()
                .map(|column| self.theme.header.apply_to(column).to_string())
                .collect(),
            grid.rows
                .iter()
                .map(|row| {
                    row.iter()
                        .map(|cell| {
                            cell.as_ref()
                                .map(|cell| self.cell_text(cell, CellLayout::Compact))
                                .unwrap_or_default()
                        })
                        .collect()
                })
                .collect(),
        )
    }

    fn expanded_text(&self, grid: &Grid) -> String {
        let key_width = grid
            .columns
            .iter()
            .map(|column| console::measure_text_width(column))
            .max()
            .unwrap_or_default();
        let mut out = String::new();
        for (position, row) in grid.rows.iter().enumerate() {
            let mut lines = Vec::new();
            for (column, cell) in grid.columns.iter().zip(row) {
                let Some(cell) = cell else { continue };
                let text = self.cell_text(cell, CellLayout::Pretty);
                for (line_number, line) in text.lines().enumerate() {
                    let key = if line_number == 0 {
                        column.as_str()
                    } else {
                        ""
                    };
                    lines.push(format!(
                        "{}{} │ {line}",
                        self.theme.key.apply_to(key),
                        " ".repeat(key_width - console::measure_text_width(key)),
                    ));
                }
            }
            let widest = lines
                .iter()
                .map(|line| console::measure_text_width(line))
                .max()
                .unwrap_or_default();
            let title = format!("-[ RECORD {} ]", position + 1);
            let padding = widest.saturating_sub(title.len()).max(1);
            out.push_str(
                &self
                    .theme
                    .muted
                    .apply_to(format!("{title}{}", "-".repeat(padding)))
                    .to_string(),
            );
            out.push('\n');
            for line in lines {
                out.push_str(&line);
                out.push('\n');
            }
        }
        out
    }

    fn cell_text(&self, cell: &Cell, layout: CellLayout) -> String {
        match (cell, layout) {
            (Cell::Value(value), CellLayout::Compact) => self.compact_value(value),
            (Cell::Value(value), CellLayout::Pretty) => self.pretty_value(value),
            (Cell::Text(text), _) => text.clone(),
            (Cell::Count(count), _) => self.theme.number.apply_to(count).to_string(),
            (Cell::Percent(share), _) => format!("{share:.1}%"),
        }
    }

    fn json_rows(&self, grid: &Grid) -> serde_json::Value {
        serde_json::Value::Array(self.json_objects(grid))
    }

    fn json_objects(&self, grid: &Grid) -> Vec<serde_json::Value> {
        grid.rows
            .iter()
            .map(|row| {
                serde_json::Value::Object(
                    grid.columns
                        .iter()
                        .zip(row)
                        .filter_map(|(column, cell)| {
                            cell.as_ref()
                                .map(|cell| (column.clone(), self.json_cell(cell)))
                        })
                        .collect(),
                )
            })
            .collect()
    }

    fn json_cell(&self, cell: &Cell) -> serde_json::Value {
        match cell {
            Cell::Value(value) => self.json_value(value),
            Cell::Text(text) => serde_json::Value::String(text.clone()),
            Cell::Count(count) => serde_json::Value::from(*count),
            Cell::Percent(share) => serde_json::json!((share * 10.0).round() / 10.0),
        }
    }
}

#[derive(Clone, Copy)]
enum CellLayout {
    Compact,
    Pretty,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::render::fixtures::{document, draft, dune, string, value, vector, DOCUMENTS_PATH};
    use crate::render::Theme;
    use firestore::gcloud_sdk::google::firestore::v1::value::ValueType;
    use firestore::gcloud_sdk::google::firestore::v1::{ArrayValue, MapValue};
    use firestore::gcloud_sdk::google::r#type::LatLng;
    use firestore::gcloud_sdk::prost_types::Timestamp;
    use std::collections::HashMap;

    fn view(theme: &Theme, format: OutputFormat, expanded: ExpandedMode) -> View<'_> {
        View {
            theme,
            format,
            expanded,
            width: None,
            documents_path: DOCUMENTS_PATH,
        }
    }

    fn books() -> Grid {
        Grid::from_documents(vec![dune(), draft()], &["title".to_string()])
    }

    #[test]
    fn documents_render_as_a_table_of_compact_cells_under_the_union_of_their_fields() {
        let theme = Theme::new(false);

        let table = view(&theme, OutputFormat::Table, ExpandedMode::Off).grid(&books());

        assert_eq!(table, TABLE);
    }

    #[test]
    fn the_expanded_view_shows_a_block_per_row_with_nested_values_pretty_printed() {
        let theme = Theme::new(false);
        let grid = Grid::from_documents(vec![draft(), dune()], &[]);

        let expanded = view(&theme, OutputFormat::Table, ExpandedMode::On).grid(&grid);

        assert_eq!(expanded, EXPANDED);
    }

    fn auto_expanded_at(width: usize, grid: &Grid) -> String {
        View {
            width: Some(width),
            ..view(&Theme::new(false), OutputFormat::Table, ExpandedMode::Auto)
        }
        .grid(grid)
    }

    #[test]
    fn auto_expands_only_a_table_wider_than_the_terminal() {
        let grid = Grid::from_documents(vec![draft()], &[]);

        assert!(auto_expanded_at(80, &grid).starts_with('╭'));
        assert!(auto_expanded_at(10, &grid).starts_with("-[ RECORD 1 ]"));
    }

    #[test]
    fn a_result_without_columns_draws_no_table() {
        let theme = Theme::new(false);
        let empty = Grid::from_documents(Vec::new(), &[]);

        for expanded in [ExpandedMode::Off, ExpandedMode::On, ExpandedMode::Auto] {
            assert_eq!(view(&theme, OutputFormat::Table, expanded).grid(&empty), "");
        }
    }

    #[test]
    fn a_result_without_rows_is_an_empty_json_array_and_no_json_lines() {
        let theme = Theme::new(false);
        let empty = Grid::from_documents(Vec::new(), &[]);

        assert_eq!(
            view(&theme, OutputFormat::Json, ExpandedMode::Off).grid(&empty),
            "[]\n"
        );
        assert_eq!(
            view(&theme, OutputFormat::Jsonl, ExpandedMode::Off).grid(&empty),
            ""
        );
    }

    fn restaurants() -> Grid {
        let restaurant = |id: &str, cuisine: &str, description: &str, menu: &str| {
            document(
                id,
                vec![
                    ("cuisine", string(cuisine)),
                    ("description", string(description)),
                    (
                        "location",
                        value(ValueType::GeoPointValue(LatLng {
                            latitude: 38.990077,
                            longitude: -107.065076,
                        })),
                    ),
                    ("menu", string(menu)),
                    ("name", string("Gluten-Free Kitchen")),
                    ("price_level", value(ValueType::IntegerValue(3))),
                    ("rating", value(ValueType::DoubleValue(4.3))),
                ],
            )
        };
        Grid::from_documents(
            vec![
                restaurant(
                    "rest-08",
                    "health",
                    "Gluten-free waffles and e-mail order specialities for every taste",
                    "gluten-free waffles, quinoa bowls, c++ and more of the same",
                ),
                restaurant(
                    "rest-04",
                    "pizza",
                    "New York style pizza by the slice.",
                    "pizza",
                ),
            ],
            &[],
        )
    }

    fn table_at(width: Option<usize>, colour: bool) -> String {
        let theme = Theme::new(colour);
        View {
            width,
            ..view(&theme, OutputFormat::Table, ExpandedMode::Off)
        }
        .grid(&restaurants())
    }

    fn line_widths(text: &str) -> Vec<usize> {
        text.lines().map(console::measure_text_width).collect()
    }

    #[test]
    fn a_table_wider_than_the_terminal_is_shrunk_to_the_terminal_width_with_its_borders_aligned() {
        for colour in [false, true] {
            let natural = line_widths(&table_at(None, colour))[0];
            for width in [80, 120, 200] {
                let table = table_at(Some(width), colour);

                assert_eq!(
                    line_widths(&table),
                    vec![width.min(natural); table.lines().count()],
                    "width {width}, colour {colour}:\n{table}"
                );
            }
        }
    }

    #[test]
    fn shrinking_cuts_cell_text_before_it_cuts_a_header() {
        let table = table_at(Some(120), false);

        let header_line = table.lines().nth(1).unwrap_or_default();
        for header in restaurants().columns() {
            assert!(header_line.contains(header.as_str()), "{header}:\n{table}");
        }
        assert_eq!(line_widths(&table).first(), Some(&120));
    }

    #[test]
    fn a_table_that_fits_the_terminal_is_drawn_at_its_natural_width() {
        assert_eq!(table_at(Some(400), true), table_at(None, true));
    }

    #[test]
    fn a_vector_is_one_cell_of_its_component_count_in_a_table_and_its_components_when_expanded() {
        let theme = Theme::new(false);
        let mut grid = Grid::new(["embedding"]);
        grid.push_row(vec![Some(Cell::Value(vector(&[0.4, 0.2, 0.9])))]);

        let table = view(&theme, OutputFormat::Table, ExpandedMode::Off).grid(&grid);
        let expanded = view(&theme, OutputFormat::Table, ExpandedMode::On).grid(&grid);

        assert!(table.contains("vector(3)"), "{table}");
        assert!(!table.contains("__type__"), "{table}");
        assert!(expanded.contains("[0.4, 0.2, 0.9]"), "{expanded}");
        assert!(!expanded.contains("__type__"), "{expanded}");
    }

    #[test]
    fn json_lines_hold_one_plain_json_object_per_row() {
        let theme = Theme::new(false);

        let lines = view(&theme, OutputFormat::Jsonl, ExpandedMode::Off).grid(&books());

        assert_eq!(lines, JSON_LINES);
    }

    #[test]
    fn json_writes_infinity_a_fractional_timestamp_and_a_vector_in_the_plain_encoding() {
        let theme = Theme::new(false);
        let mut grid = Grid::new(["score", "seen", "embedding"]);
        grid.push_row(vec![
            Some(Cell::Value(value(ValueType::DoubleValue(f64::INFINITY)))),
            Some(Cell::Value(value(ValueType::TimestampValue(Timestamp {
                seconds: 1_700_000_000,
                nanos: 500_000_000,
            })))),
            Some(Cell::Value(value(ValueType::MapValue(MapValue {
                fields: HashMap::from([
                    ("__type__".to_string(), string("__vector__")),
                    (
                        "value".to_string(),
                        value(ValueType::ArrayValue(ArrayValue {
                            values: vec![
                                value(ValueType::DoubleValue(1.0)),
                                value(ValueType::DoubleValue(2.5)),
                            ],
                        })),
                    ),
                ]),
            })))),
        ]);

        let lines = view(&theme, OutputFormat::Jsonl, ExpandedMode::Off).grid(&grid);

        assert_eq!(
            lines,
            "{\"score\":\"Infinity\",\"seen\":\"2023-11-14T22:13:20.500Z\",\"embedding\":[1.0,2.5]}\n"
        );
    }

    #[test]
    fn several_grids_render_as_one_json_object_of_arrays_by_title() {
        let theme = Theme::new(false);
        let mut first = Grid::new(["id"]);
        first.push_row(vec![Some(Cell::Count(1))]);
        let second = Grid::new(["name"]);

        let json = view(&theme, OutputFormat::Json, ExpandedMode::Off)
            .grids(&[("indexes", &first), ("fields", &second)]);

        assert_eq!(
            serde_json::from_str::<serde_json::Value>(&json).expect("JSON"),
            serde_json::json!({"indexes": [{"id": 1}], "fields": []})
        );
    }

    fn grid_of(fields: Vec<(&str, Value)>) -> Grid {
        Grid::from_documents(vec![document("dune", fields)], &[])
    }

    fn hinted(grid: &Grid, expanded: ExpandedMode, width: Option<usize>) -> bool {
        let theme = Theme::new(false);
        let hint = View {
            width,
            ..view(&theme, OutputFormat::Table, expanded)
        }
        .detail_hint(grid);
        !hint.is_empty()
    }

    #[test]
    fn a_table_that_showed_every_value_whole_has_no_hint() {
        let grid = grid_of(vec![
            ("title", string("Dune")),
            ("rating", value(ValueType::DoubleValue(4.5))),
            ("forty", string(&"x".repeat(40))),
            ("empty_map", value(ValueType::MapValue(MapValue::default()))),
            (
                "empty_array",
                value(ValueType::ArrayValue(ArrayValue::default())),
            ),
        ]);

        assert!(!hinted(&grid, ExpandedMode::Off, Some(400)));
        assert!(!hinted(&grid, ExpandedMode::Off, None));
    }

    #[test]
    fn a_table_hides_detail_when_a_cell_is_cut_or_only_summarises_its_value() {
        let nested = value(ValueType::MapValue(MapValue {
            fields: HashMap::from([("city".to_string(), string("London"))]),
        }));
        let list = value(ValueType::ArrayValue(ArrayValue {
            values: vec![string("sf")],
        }));
        for hidden in [
            string(&"x".repeat(41)),
            nested,
            list,
            value(ValueType::BytesValue(vec![1, 2, 3])),
        ] {
            let grid = grid_of(vec![("title", string("Dune")), ("field", hidden)]);

            assert!(hinted(&grid, ExpandedMode::Off, None), "{grid:?}");
        }
    }

    #[test]
    fn a_table_cut_to_fit_the_terminal_has_a_hint_and_one_that_fits_has_none() {
        let grid = grid_of(vec![
            ("title", string("Dune")),
            ("author", string("Frank Herbert of Dune")),
        ]);

        assert!(hinted(&grid, ExpandedMode::Off, Some(20)));
        assert!(!hinted(&grid, ExpandedMode::Off, Some(80)));
    }

    #[test]
    fn a_result_drawn_as_records_whole_has_no_hint() {
        let grid = grid_of(vec![("author", string(&"x".repeat(60)))]);

        assert!(hinted(&grid, ExpandedMode::Auto, Some(80)));
        assert!(!hinted(&grid, ExpandedMode::Auto, Some(20)));
        assert!(!hinted(&grid, ExpandedMode::On, Some(80)));
        assert!(!hinted(&grid, ExpandedMode::Full, Some(80)));
    }

    #[test]
    fn json_output_has_no_hint() {
        let grid = grid_of(vec![("author", string(&"x".repeat(60)))]);
        let theme = Theme::new(false);

        for format in [OutputFormat::Json, OutputFormat::Jsonl] {
            assert_eq!(
                view(&theme, format, ExpandedMode::Off).detail_hint(&grid),
                ""
            );
        }
    }

    const TABLE: &str = r#"╭─────────────┬──────────┬─────────────┬─────────────────┬──────────────────────────────────────────┬─────────┬──────────┬───────────────┬───────┬──────────────────────┬────────┬──────────┬───────────╮
│ __name__    ┆ title    ┆ address     ┆ author          ┆ blurb                                    ┆ cover   ┆ in_print ┆ location      ┆ pages ┆ published            ┆ rating ┆ subtitle ┆ tags      │
╞═════════════╪══════════╪═════════════╪═════════════════╪══════════════════════════════════════════╪═════════╪══════════╪═══════════════╪═══════╪══════════════════════╪════════╪══════════╪═══════════╡
│ books/dune  ┆ Dune     ┆ {city, zip} ┆ authors/herbert ┆ A desert planet, a s…e,↵and a duke's son ┆ 4 bytes ┆ true     ┆ (51.5, -0.12) ┆ 412   ┆ 2023-11-14T22:13:20Z ┆ 4.5    ┆ NULL     ┆ [2 items] │
│ books/draft ┆ Untitled ┆             ┆                 ┆                                          ┆         ┆          ┆               ┆       ┆                      ┆        ┆          ┆           │
╰─────────────┴──────────┴─────────────┴─────────────────┴──────────────────────────────────────────┴─────────┴──────────┴───────────────┴───────┴──────────────────────┴────────┴──────────┴───────────╯
"#;

    const EXPANDED: &str = r#"-[ RECORD 1 ]----------
__name__  │ books/draft
title     │ Untitled
-[ RECORD 2 ]------------------------------------------
__name__  │ books/dune
address   │ {
          │   "city": "London",
          │   "zip": "N1 9GU"
          │ }
author    │ authors/herbert
blurb     │ A desert planet, a spice that extends life,
          │ and a duke's son
cover     │ 4 bytes
in_print  │ true
location  │ (51.5, -0.12)
pages     │ 412
published │ 2023-11-14T22:13:20Z
rating    │ 4.5
subtitle  │ NULL
tags      │ [
          │   "sf",
          │   "classic"
          │ ]
title     │ Dune
"#;

    const JSON_LINES: &str = r#"{"__name__":"books/dune","title":"Dune","address":{"city":"London","zip":"N1 9GU"},"author":"authors/herbert","blurb":"A desert planet, a spice that extends life,\nand a duke's son","cover":"AQID/w==","in_print":true,"location":{"latitude":51.5,"longitude":-0.12},"pages":412,"published":"2023-11-14T22:13:20Z","rating":4.5,"subtitle":null,"tags":["sf","classic"]}
{"__name__":"books/draft","title":"Untitled"}
"#;
}