vantage-cli-util 0.4.6

CLI utilities for Vantage data framework
Documentation
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
//! End-to-end test of the Vista CLI runner against an in-memory
//! `MockShell` Vista. Covers the paths wired to real `Vista` calls:
//! eq filter, `id=` alias, `[N]` narrow, `[+col]` sort, `?keyword`
//! search, locator dispatch, and the three output formats. Parser
//! behaviour for the still-stubbed paths (non-`eq` operators,
//! `[N:M]` range slicing, aggregates) is covered in `parse.rs` unit
//! tests — no need to re-assert it here.

use ciborium::Value as CborValue;
use indexmap::IndexMap;
use std::sync::Mutex;

use vantage_cli_util::output::{self, OutputFormat};
use vantage_cli_util::vista_cli::{self, AggregateOp, Mode, ModelFactory, Renderer};
use vantage_types::Record;
use vantage_vista::mocks::MockShell;
use vantage_vista::{Column, Vista, VistaMetadata};

// ─── Test fixtures ─────────────────────────────────────────────────────────

fn cbor_text(s: &str) -> CborValue {
    CborValue::Text(s.into())
}

fn record(pairs: &[(&str, CborValue)]) -> Record<CborValue> {
    let mut r = Record::new();
    for (k, v) in pairs {
        r.insert((*k).to_string(), v.clone());
    }
    r
}

fn seeded_shell() -> MockShell {
    // Ids match the declared "String" column type so column-typed value
    // coercion (`id=2` → Text("2")) lines up with what MockShell's strict
    // CBOR-eq filter compares against.
    MockShell::new()
        .with_record(
            "1",
            record(&[
                ("id", cbor_text("1")),
                ("name", cbor_text("Alice")),
                ("salary", CborValue::Integer(900.into())),
                ("vip_flag", CborValue::Bool(true)),
            ]),
        )
        .with_record(
            "2",
            record(&[
                ("id", cbor_text("2")),
                ("name", cbor_text("Bob")),
                ("salary", CborValue::Integer(2500.into())),
                ("vip_flag", CborValue::Bool(false)),
            ]),
        )
        .with_record(
            "3",
            record(&[
                ("id", cbor_text("3")),
                ("name", cbor_text("Carol")),
                ("salary", CborValue::Integer(1500.into())),
                ("vip_flag", CborValue::Bool(true)),
            ]),
        )
        // A user whose name is literally the string "true" — proves that
        // column-typed coercion keeps `name=true` as text. Without the
        // coercion this row would never match `name=true`.
        .with_record(
            "4",
            record(&[
                ("id", cbor_text("4")),
                ("name", cbor_text("true")),
                ("salary", CborValue::Integer(0.into())),
                ("vip_flag", CborValue::Bool(false)),
            ]),
        )
}

fn build_users_vista() -> Vista {
    let metadata = VistaMetadata::new()
        .with_column(Column::new("id", "String").with_flag("id"))
        .with_column(
            Column::new("name", "String")
                .with_flag("title")
                .with_flag("orderable")
                .with_flag("searchable"),
        )
        .with_column(Column::new("salary", "i64").with_flag("orderable"))
        .with_column(Column::new("vip_flag", "bool"))
        .with_id_column("id");
    Vista::new("users", Box::new(seeded_shell().with_metadata(metadata)))
}

// ─── Test factory + recorder ───────────────────────────────────────────────

struct TestFactory;

impl ModelFactory for TestFactory {
    fn for_name(&self, name: &str) -> Option<(Vista, Mode)> {
        match name {
            "users" => Some((build_users_vista(), Mode::List)),
            "user" => Some((build_users_vista(), Mode::Single)),
            _ => None,
        }
    }

    fn for_locator(&self, locator: &str) -> Option<Vista> {
        // Accept `user:<id>` (SurrealDB-style Thing) and narrow the
        // standard users vista to that id. Route through the same
        // column-typed coercion the CLI uses on `field=value` so the
        // value matches the id column's declared type.
        let id = locator.strip_prefix("user:")?;
        let mut v = build_users_vista();
        let coerced = vista_cli::coerce_for_column(&v, "id", id).ok()?;
        v.add_condition_eq("id", coerced).ok()?;
        Some(v)
    }
}

#[derive(Default)]
struct Recorder {
    stubs: Mutex<Vec<String>>,
    lists: Mutex<Vec<String>>,
    records: Mutex<Vec<String>>,
    scalars: Mutex<Vec<String>>,
    format: OutputFormat,
}

impl Recorder {
    fn with_format(format: OutputFormat) -> Self {
        Self {
            format,
            ..Default::default()
        }
    }
    fn stubs(&self) -> Vec<String> {
        self.stubs.lock().unwrap().clone()
    }
    fn lists(&self) -> Vec<String> {
        self.lists.lock().unwrap().clone()
    }
    fn records(&self) -> Vec<String> {
        self.records.lock().unwrap().clone()
    }
}

impl Renderer for Recorder {
    fn render_list(
        &self,
        _vista: &Vista,
        records: &IndexMap<String, Record<CborValue>>,
        _column_override: Option<&[String]>,
    ) {
        self.lists
            .lock()
            .unwrap()
            .push(output::render_list(self.format, records));
    }

    fn render_record(
        &self,
        _vista: &Vista,
        id: &str,
        record: &Record<CborValue>,
        _relations: &[String],
    ) {
        self.records
            .lock()
            .unwrap()
            .push(output::render_record(self.format, id, record));
    }

    fn render_scalar(
        &self,
        _vista: &Vista,
        op: AggregateOp,
        field: Option<&str>,
        value: &CborValue,
    ) {
        let label = match field {
            Some(f) => format!("{}({f})", op.name()),
            None => format!("{}()", op.name()),
        };
        self.scalars
            .lock()
            .unwrap()
            .push(output::render_scalar(self.format, &label, value));
    }

    fn note_stub(&self, what: &str) {
        self.stubs.lock().unwrap().push(what.to_string());
    }
}

fn argv(parts: &[&str]) -> Vec<String> {
    parts.iter().map(|s| s.to_string()).collect()
}

// ─── Tests ─────────────────────────────────────────────────────────────────

#[tokio::test]
async fn plain_list_renders_all_records() {
    let rec = Recorder::with_format(OutputFormat::CborDiag);
    vista_cli::run(&TestFactory, &rec, &argv(&["users"]))
        .await
        .unwrap();

    assert!(
        rec.stubs().is_empty(),
        "no stubs expected, got {:?}",
        rec.stubs()
    );
    let lists = rec.lists();
    assert_eq!(lists.len(), 1);
    // Three records, Alice/Bob/Carol all present (cbor-diag is stable).
    assert!(lists[0].contains("\"Alice\""));
    assert!(lists[0].contains("\"Bob\""));
    assert!(lists[0].contains("\"Carol\""));
}

#[tokio::test]
async fn eq_filter_narrows_results() {
    let rec = Recorder::with_format(OutputFormat::CborDiag);
    vista_cli::run(&TestFactory, &rec, &argv(&["users", "vip_flag=true"]))
        .await
        .unwrap();

    let lists = rec.lists();
    assert_eq!(lists.len(), 1);
    assert!(lists[0].contains("\"Alice\""));
    assert!(!lists[0].contains("\"Bob\""));
    assert!(lists[0].contains("\"Carol\""));
}

#[tokio::test]
async fn eq_on_string_column_keeps_text_even_when_value_looks_like_bool() {
    // Without column-typed coercion, `name=true` would auto-detect to
    // `Bool(true)` and miss row id=4 (whose name is literally the string
    // "true"). The runner consults the `name` column's declared type
    // (`String`) and produces `Text("true")`, which matches.
    let rec = Recorder::with_format(OutputFormat::CborDiag);
    vista_cli::run(&TestFactory, &rec, &argv(&["users", "name=true"]))
        .await
        .unwrap();

    let lists = rec.lists();
    assert_eq!(lists.len(), 1);
    let rendered = &lists[0];
    // Only the row whose name is the text "true" comes back.
    assert!(rendered.contains("\"4\""), "got: {rendered}");
    assert!(!rendered.contains("\"Alice\""), "got: {rendered}");
    assert!(!rendered.contains("\"Bob\""), "got: {rendered}");

    // Sanity-check the other direction: bool column still gets a bool.
    let rec2 = Recorder::with_format(OutputFormat::CborDiag);
    vista_cli::run(&TestFactory, &rec2, &argv(&["users", "vip_flag=true"]))
        .await
        .unwrap();
    let lists2 = rec2.lists();
    assert!(lists2[0].contains("\"Alice\""), "got: {}", lists2[0]); // vip
    assert!(!lists2[0].contains("\"Bob\""), "got: {}", lists2[0]); // not vip
}

#[tokio::test]
async fn typed_bool_works_same_as_autodetect() {
    let rec = Recorder::with_format(OutputFormat::CborDiag);
    vista_cli::run(&TestFactory, &rec, &argv(&["users", "vip_flag=#true"]))
        .await
        .unwrap();

    let lists = rec.lists();
    assert!(lists[0].contains("\"Alice\""));
    assert!(!lists[0].contains("\"Bob\""));
}

#[tokio::test]
async fn id_alias_forces_single_mode() {
    let rec = Recorder::with_format(OutputFormat::CborDiag);
    vista_cli::run(&TestFactory, &rec, &argv(&["users", "id=2"]))
        .await
        .unwrap();

    assert!(rec.lists().is_empty());
    let records = rec.records();
    assert_eq!(records.len(), 1);
    assert!(records[0].contains("\"Bob\""));
}

#[tokio::test]
async fn index_narrows_to_single() {
    let rec = Recorder::with_format(OutputFormat::CborDiag);
    vista_cli::run(&TestFactory, &rec, &argv(&["users[0]"]))
        .await
        .unwrap();

    let records = rec.records();
    assert_eq!(records.len(), 1);
    assert!(records[0].contains("\"Alice\""));
}

#[tokio::test]
async fn sort_applies_via_add_order() {
    let rec = Recorder::with_format(OutputFormat::CborDiag);
    vista_cli::run(&TestFactory, &rec, &argv(&["users", "[+name]"]))
        .await
        .unwrap();

    assert!(
        rec.stubs().is_empty(),
        "sort is wired to Vista::add_order, no stub expected: {:?}",
        rec.stubs()
    );
    // MockShell honours add_order, so the rendered list comes back in
    // name-ascending order: Alice, Bob, Carol.
    let lists = rec.lists();
    assert_eq!(lists.len(), 1);
    let rendered = &lists[0];
    let alice = rendered.find("Alice").expect("Alice present");
    let bob = rendered.find("Bob").expect("Bob present");
    let carol = rendered.find("Carol").expect("Carol present");
    assert!(alice < bob && bob < carol, "got: {rendered}");
}

#[tokio::test]
async fn sort_then_index_narrows_to_single() {
    // [+name:0] — sort, then `apply_index` narrows to the top row. With
    // sort wired through `Vista::add_order`, "row 0" is the smallest
    // by name-ascending, which is Alice (matches seed order here too).
    let rec = Recorder::with_format(OutputFormat::CborDiag);
    vista_cli::run(&TestFactory, &rec, &argv(&["users[+name:0]"]))
        .await
        .unwrap();

    assert!(rec.stubs().is_empty(), "stubs: {:?}", rec.stubs());
    let records = rec.records();
    assert_eq!(records.len(), 1);
    assert!(records[0].contains("\"Alice\""));
}

#[tokio::test]
async fn search_applies_via_add_search() {
    let rec = Recorder::with_format(OutputFormat::CborDiag);
    vista_cli::run(&TestFactory, &rec, &argv(&["users", "?alice"]))
        .await
        .unwrap();

    assert!(
        rec.stubs().is_empty(),
        "search is wired to Vista::add_search, no stub expected: {:?}",
        rec.stubs()
    );
    // MockShell honours add_search with case-insensitive substring
    // matching across text fields — so "?alice" leaves only Alice.
    let lists = rec.lists();
    assert_eq!(lists.len(), 1);
    let rendered = &lists[0];
    assert!(rendered.contains("Alice"), "got: {rendered}");
    assert!(!rendered.contains("Bob"), "got: {rendered}");
    assert!(!rendered.contains("Carol"), "got: {rendered}");
}

#[tokio::test]
async fn aggregate_must_be_terminal() {
    let rec = Recorder::with_format(OutputFormat::CborDiag);
    let err = vista_cli::run(
        &TestFactory,
        &rec,
        &argv(&["users", "@sum:salary", "vip_flag=true"]),
    )
    .await
    .unwrap_err();
    assert!(format!("{err}").contains("Aggregate token"));
}

#[tokio::test]
async fn locator_resolves_via_for_locator() {
    let rec = Recorder::with_format(OutputFormat::CborDiag);
    vista_cli::run(&TestFactory, &rec, &argv(&["user:2"]))
        .await
        .unwrap();

    let records = rec.records();
    assert_eq!(records.len(), 1);
    assert!(records[0].contains("\"Bob\""));
}

#[tokio::test]
async fn locator_unknown_scheme_errors() {
    let rec = Recorder::with_format(OutputFormat::CborDiag);
    let err = vista_cli::run(&TestFactory, &rec, &argv(&["arn:aws:unknown"]))
        .await
        .unwrap_err();
    assert!(format!("{err}").contains("Cannot resolve locator"));
}

#[tokio::test]
async fn cbor_diag_output_round_trips_record() {
    let rec = Recorder::with_format(OutputFormat::CborDiag);
    vista_cli::run(&TestFactory, &rec, &argv(&["users", "id=1"]))
        .await
        .unwrap();

    let records = rec.records();
    // Strict equality on cbor-diag — this is the format third-party
    // drivers must match byte-for-byte in their bakery example tests.
    // `Record<CborValue>` preserves insertion order from the seed, so
    // the field ordering is stable.
    assert_eq!(
        records[0],
        "\"1\": {\"id\": \"1\", \"name\": \"Alice\", \"salary\": 900, \"vip_flag\": true}\n"
    );
}

#[tokio::test]
async fn json_output_keeps_int_and_bool() {
    let rec = Recorder::with_format(OutputFormat::Json);
    vista_cli::run(&TestFactory, &rec, &argv(&["users", "id=1"]))
        .await
        .unwrap();

    let records = rec.records();
    // JSON: bool, int (fits in i64), and string fields all serialise faithfully.
    assert_eq!(
        records[0],
        "{\"1\":{\"id\":\"1\",\"name\":\"Alice\",\"salary\":900,\"vip_flag\":true}}\n"
    );
}

#[tokio::test]
async fn ndjson_output_one_line_per_record() {
    let rec = Recorder::with_format(OutputFormat::Ndjson);
    vista_cli::run(&TestFactory, &rec, &argv(&["users"]))
        .await
        .unwrap();

    let lists = rec.lists();
    assert_eq!(lists.len(), 1);
    let lines: Vec<&str> = lists[0].lines().collect();
    assert_eq!(lines.len(), 4);
    assert!(lines[0].starts_with("{\"_id\":\"1\","));
}