qua 0.68.0

Structure-aware query CLI for the Quarb engine
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
//! The multi-mount flow carries the same JSON-column graft as the
//! single-input flow: `open_target` wraps relational adapters in
//! ComposeAdapter (a regression — mounts once returned the column
//! text flat while the single input grafted it).

use qua::{OpenOpts, open_target};
use quarb::{AstAdapter, NodeId, Value};

/// Forward the boxed mount through the trait (the session tools'
/// Dyn wrapper, locally).
struct Dyn(Box<dyn AstAdapter>);

impl AstAdapter for Dyn {
    fn root(&self) -> NodeId {
        self.0.root()
    }
    fn children(&self, n: NodeId) -> Vec<NodeId> {
        self.0.children(n)
    }
    fn name(&self, n: NodeId) -> Option<String> {
        self.0.name(n)
    }
    fn parent(&self, n: NodeId) -> Option<NodeId> {
        self.0.parent(n)
    }
    fn property(&self, n: NodeId, key: &str) -> Option<Value> {
        self.0.property(n, key)
    }
    fn default_value(&self, n: NodeId) -> Option<Value> {
        self.0.default_value(n)
    }
    fn traits(&self, n: NodeId) -> Vec<String> {
        self.0.traits(n)
    }
    fn has_trait(&self, n: NodeId, name: &str) -> bool {
        self.0.has_trait(n, name)
    }
    fn metadata(&self, n: NodeId, key: &str) -> Option<Value> {
        self.0.metadata(n, key)
    }
}

#[test]
fn mounted_sqlite_grafts_json_columns() {
    let dir = std::env::temp_dir().join("qua-mount-graft-test");
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("g.db");
    let _ = std::fs::remove_file(&path);
    {
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch(
            r#"CREATE TABLE s (id INTEGER PRIMARY KEY, meta JSON, note TEXT);
             INSERT INTO s VALUES
               (1,'{"device":"phone","geo":{"city":"London"}}','{"geo":{"city":"Paris"}}'),
               (2,'{"device":"laptop","geo":{"city":"Berlin"}}','{"geo":{"city":"Rome"}}');"#,
        )
        .unwrap();
    }
    let adapter = open_target(path.to_str().unwrap(), &OpenOpts::default())
        .expect("mount")
        .adapter;
    let adapter = Dyn(adapter);
    let run = |q: &str| -> Vec<String> {
        match quarb::run(q, &adapter).unwrap() {
            quarb::QueryResult::Values(vs) => vs.iter().map(|v| v.to_string()).collect(),
            _ => panic!("expected values"),
        }
    };
    // Navigation into the column, a filter over it, and dual
    // exposure at the graft root — all through the mount door. The
    // column typed JSON declares its cells' notation (spec:
    // Grafting).
    assert_eq!(run("/s/1/meta/geo/city::"), ["London"]);
    assert_eq!(run("/s/*[/meta/geo/city:: = \"Berlin\"]::id"), ["2"]);
    assert_eq!(run("/s/2/meta::device"), ["laptop"]);
    // What the cell answers as properties it lists as its own: the
    // names of the graft's root, as one step in (`:props` was empty
    // at the graft and right at `/meta/geo`).
    assert_eq!(run("/s/2/meta | :props"), ["device, geo"]);
    assert_eq!(run("/s/2/meta/geo | :props"), ["city"]);
    assert_eq!(run("/s/*/meta | :props | ... @| unique"), ["device", "geo"]);
    // a cell that grafts nothing lists nothing
    assert_eq!(run("/s/2/id | :props | ... @| count"), ["0"]);
    assert_eq!(run("/s/2/note | :props | ... @| count"), ["0"]);
    // A TEXT column full of JSON declares nothing: its cell is a
    // leaf, a path through it is empty; the query's `<json>` at the
    // step reads it.
    assert_eq!(run("/s/1/note/geo/city::"), Vec::<String>::new());
    assert_eq!(run("/s/1/note::"), [r#"{"geo":{"city":"Paris"}}"#]);
    assert_eq!(run("/s/1/note<json>/geo/city::"), ["Paris"]);
    assert_eq!(run("/s/*/note<json>/geo/city::"), ["Paris", "Rome"]);
}

/// `?doc=PATH` on a reading prefix over a source that is no directory
/// (spec: The Corpus Reading): each leaf the path reaches is a
/// document, its text read as prose with the corpus tokens, the row's
/// other columns riding as its declarations.
#[test]
fn rows_read_as_documents_with_doc() {
    let dir = std::env::temp_dir().join("qua-mount-doc-test");
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("blog.db");
    let _ = std::fs::remove_file(&path);
    {
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch(
            r#"CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT, author TEXT, body TEXT);
             INSERT INTO posts VALUES
               (1,'Ithaca','Homer','Tell me, Muse, of the man of many ways. He wandered far.'),
               (2,'Troy','Homer','Sing, goddess, the anger of Achilles.');"#,
        )
        .unwrap();
    }
    let opts = OpenOpts::default();
    let target = format!("corpus:{}?doc=posts/*/body", path.display());
    let a = Dyn(open_target(&target, &opts).expect("mount").adapter);
    assert_eq!(run_q(&a, "/posts/*/body::head:title"), ["Ithaca", "Troy"]);
    assert_eq!(run_q(&a, "/posts/1/body::head:author"), ["Homer"]);
    assert_eq!(run_q(&a, "/posts/1/body//sentence @| count"), ["2"]);
    assert_eq!(run_q(&a, "/posts/2/body//token @| count"), ["9"]);
    assert_eq!(run_q(&a, "/posts/*/title::"), ["Ithaca", "Troy"]);
    // the text reading, without tokens
    let t = Dyn(
        open_target(&format!("text:{}?doc=posts/*/body", path.display()), &opts)
            .expect("mount")
            .adapter,
    );
    assert_eq!(
        run_q(&t, "/posts/2/body//paragraph::"),
        ["Sing, goddess, the anger of Achilles."]
    );
    assert_eq!(run_q(&t, "/posts/2/body//token @| count"), ["0"]);
    // a path reaching no leaf is refused
    let err = open_target(
        &format!("corpus:{}?doc=posts/*/nothing", path.display()),
        &opts,
    )
    .err()
    .map(|e| e.to_string())
    .unwrap_or_default();
    assert!(err.contains("names no leaf"), "{err}");
}

/// A leaf grafts only as declared (spec: Grafting): by its name's
/// extension, by what its bytes say of themselves (an XML
/// declaration, a DOCTYPE), by the mount's `?format=`, or by the
/// query's `<NOTATION>` at the step. A nameless leaf holding JSON
/// declares nothing and stays a leaf.
#[test]
fn a_leaf_grafts_only_as_declared() {
    let dir = std::env::temp_dir().join("qua-mount-declared-test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("a.json"), r#"{"k":"named"}"#).unwrap();
    std::fs::write(dir.join("b"), r#"{"k":"bare"}"#).unwrap();
    std::fs::write(
        dir.join("c"),
        "<?xml version=\"1.0\"?><root><x>decl</x></root>",
    )
    .unwrap();
    std::fs::write(
        dir.join("d"),
        "<!DOCTYPE html><html><body><p>doc</p></body></html>",
    )
    .unwrap();
    std::fs::write(dir.join("e"), "<root><x>guess</x></root>").unwrap();
    let opts = OpenOpts {
        graft: true,
        ..OpenOpts::default()
    };
    let mount = |target: &str| Dyn(open_target(target, &opts).expect("mount").adapter);
    let a = mount(dir.to_str().unwrap());
    assert_eq!(run_q(&a, "/a.json/k::"), ["named"]);
    assert_eq!(run_q(&a, "/b/k::"), Vec::<String>::new());
    assert_eq!(run_q(&a, "/b::"), [r#"{"k":"bare"}"#]);
    assert_eq!(run_q(&a, "/b<json>/k::"), ["bare"]);
    assert_eq!(run_q(&a, "/c/root/x::"), ["decl"]);
    assert_eq!(run_q(&a, "//p::"), ["doc"]);
    assert_eq!(run_q(&a, "/e/root/x::"), Vec::<String>::new());
    assert_eq!(run_q(&a, "/e<xml>/root/x::"), ["guess"]);
    // the mount's `?format=` covers every leaf beneath
    let j = mount(&format!("{}?format=json", dir.display()));
    assert_eq!(run_q(&j, "/b/k::"), ["bare"]);
    assert_eq!(run_q(&j, "/a.json/k::"), ["named"]);
    // a format no notation answers to is refused naming the list
    let err = open_target(&format!("{}?format=jsonx", dir.display()), &opts)
        .err()
        .map(|e| e.to_string())
        .unwrap_or_default();
    assert!(
        err.contains("names no notation") && err.contains("json, jsonl"),
        "{err}"
    );
}

/// `?graft=json2` on a mount (ruling 2026-11-17): the grafts the
/// mount makes of its own leaves and cells read under the property
/// reading, the step's `<json>` among them; a folder's JSON leaves
/// alike.
#[test]
fn mount_graft_option_selects_the_property_reading() {
    let dir = std::env::temp_dir().join("qua-mount-graft-option-test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("g.db");
    {
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch(
            r#"CREATE TABLE s (id INTEGER PRIMARY KEY, meta JSON, note TEXT);
             INSERT INTO s VALUES
               (1,'{"device":"phone","geo":{"city":"London"}}','{"geo":{"city":"Paris"}}'),
               (2,'{"device":"laptop","geo":{"city":"Berlin"}}','{"geo":{"city":"Rome"}}');"#,
        )
        .unwrap();
    }
    let db = path.to_str().unwrap();
    let mount =
        |target: &str, opts: &OpenOpts| Dyn(open_target(target, opts).expect("mount").adapter);
    let plain = mount(db, &OpenOpts::default());
    assert_eq!(run_q(&plain, "/s/1/meta/geo/city::"), ["London"]);
    assert_eq!(run_q(&plain, "/s/1/meta/* @| count"), ["2"]);

    let j2 = mount(&format!("{db}?graft=json2"), &OpenOpts::default());
    assert_eq!(run_q(&j2, "/s/1/meta/geo::city"), ["London"]);
    assert_eq!(run_q(&j2, "/s/1/meta/geo/city::"), Vec::<String>::new());
    assert_eq!(run_q(&j2, "/s/1/meta/* @| count"), ["1"]);
    assert_eq!(run_q(&j2, "/s/*[/meta/geo::city = \"Berlin\"]::id"), ["2"]);
    assert_eq!(run_q(&j2, "/s/1/note<json>/geo::city"), ["Paris"]);
    assert_eq!(
        run_q(&j2, "/s/1/note<json>/geo/city::"),
        Vec::<String>::new()
    );

    // a folder: its JSON leaves, the YAML ones as before
    std::fs::write(dir.join("a.json"), r#"{"k":"named","in":{"n":1}}"#).unwrap();
    std::fs::write(dir.join("b.yaml"), "k: named\nin:\n  n: 1\n").unwrap();
    let opts = OpenOpts {
        graft: true,
        ..OpenOpts::default()
    };
    let f = mount(&format!("{}?graft=json2", dir.display()), &opts);
    assert_eq!(run_q(&f, "/a.json::k"), ["named"]);
    assert_eq!(run_q(&f, "/a.json/* @| count"), ["1"]);
    assert_eq!(run_q(&f, "/b.yaml/* @| count"), ["2"]);
    let f = mount(&format!("{}?graft=json2,yaml2", dir.display()), &opts);
    assert_eq!(run_q(&f, "/b.yaml/* @| count"), ["1"]);
}

/// `?crosslinks=LABEL` on a database file (ruling 2026-11-17): the
/// references of the named labels are held in memory; a label the
/// database does not carry is refused at the open, and so is the
/// option on a source that is no database.
#[test]
fn mount_crosslinks_option_holds_the_named_references() {
    let dir = std::env::temp_dir().join("qua-mount-crosslinks-option-test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("poem.db");
    {
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch(
            "CREATE TABLE cantos (id INTEGER PRIMARY KEY, title TEXT);
             CREATE TABLE lines (id INTEGER PRIMARY KEY,
                 canto_id INTEGER REFERENCES cantos(id), text TEXT);
             INSERT INTO cantos VALUES (1, 'canto 1'), (2, 'canto 2');
             INSERT INTO lines VALUES (1, 1, 'a'), (2, 1, 'b'), (3, 2, 'c'), (4, NULL, 'd');",
        )
        .unwrap();
    }
    let db = path.to_str().unwrap();
    let opts = OpenOpts::default();
    // the mounted adapter itself: this file's `Dyn` forwards no
    // link step
    let run = |target: &str, q: &str| -> Vec<String> {
        let a = open_target(target, &opts).expect("mount").adapter;
        match quarb::run(q, &a).unwrap() {
            quarb::QueryResult::Values(vs) => vs.iter().map(|v| v.to_string()).collect(),
            _ => panic!("expected values"),
        }
    };
    let q = "/cantos/1<-canto @| count | %(n = $_; whole = (^/lines:::loaded))";
    assert_eq!(run(db, q), ["%(n = 2; whole = false)"]);
    assert_eq!(
        run(&format!("{db}?crosslinks=canto"), q),
        ["%(n = 2; whole = true)"]
    );
    let refused = |target: &str| {
        open_target(target, &opts)
            .err()
            .map(|e| e.to_string())
            .unwrap_or_default()
    };
    let err = refused(&format!("{db}?crosslinks=verse"));
    assert!(
        err.contains("no reference of this database is labelled \"verse\" (its labels: canto)"),
        "{err}"
    );
    let err = refused(&format!("{db}?crosslinks="));
    assert!(err.contains("as in ?crosslinks=order,customer"), "{err}");
    std::fs::write(dir.join("a.json"), r#"{"k": 1}"#).unwrap();
    let err = refused(&format!(
        "{}?crosslinks=canto",
        dir.join("a.json").display()
    ));
    assert!(err.contains("this source declares none"), "{err}");
}

/// The graft rename's semantics, through the same mount door:
/// `graft` opts a directory in, `no_graft` holds every boundary
/// opaque, and `code:` refuses the contradiction.
fn run_q(adapter: &Dyn, q: &str) -> Vec<String> {
    match quarb::run(q, adapter).unwrap() {
        quarb::QueryResult::Values(vs) => vs.iter().map(|v| v.to_string()).collect(),
        _ => panic!("expected values"),
    }
}

#[test]
fn dir_mount_grafts_only_with_graft() {
    let dir = std::env::temp_dir().join("qua-mount-dir-graft-test");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("cfg.json"), r#"{"port": 8080}"#).unwrap();

    let a = open_target(dir.to_str().unwrap(), &OpenOpts::default())
        .expect("mount")
        .adapter;
    assert!(
        run_q(&Dyn(a), "/cfg.json/port::").is_empty(),
        "bare dir must !graft"
    );

    let opts = OpenOpts {
        graft: true,
        ..OpenOpts::default()
    };
    let a = open_target(dir.to_str().unwrap(), &opts)
        .expect("mount")
        .adapter;
    assert_eq!(run_q(&Dyn(a), "/cfg.json/port::"), ["8080"]);
}

#[test]
fn archive_no_graft_holds_members_opaque() {
    use std::io::Write;
    let dir = std::env::temp_dir().join("qua-mount-archive-graft-test");
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("a.zip");
    let f = std::fs::File::create(&path).unwrap();
    let mut z = zip::ZipWriter::new(f);
    let o = zip::write::SimpleFileOptions::default();
    z.start_file("cfg.json", o).unwrap();
    z.write_all(br#"{"port": 8080}"#).unwrap();
    z.finish().unwrap();

    // Composed by default: the member's parsed tree grafts.
    let a = open_target(path.to_str().unwrap(), &OpenOpts::default())
        .expect("mount")
        .adapter;
    assert_eq!(run_q(&Dyn(a), "/cfg.json/port::"), ["8080"]);

    // no_graft: the tar -t view — members listed, sized, opaque.
    let opts = OpenOpts {
        no_graft: true,
        ..OpenOpts::default()
    };
    let a = open_target(path.to_str().unwrap(), &opts)
        .expect("mount")
        .adapter;
    let a = Dyn(a);
    assert!(
        run_q(&a, "/cfg.json/port::").is_empty(),
        "no_graft must !cross the boundary"
    );
    assert_eq!(
        run_q(&a, "/cfg.json:::size").len(),
        1,
        "the member stays listable && sizable"
    );
}

#[test]
fn sqlite_no_graft_keeps_columns_flat() {
    let dir = std::env::temp_dir().join("qua-mount-no-graft-sql-test");
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("g.db");
    let _ = std::fs::remove_file(&path);
    {
        let conn = rusqlite::Connection::open(&path).unwrap();
        conn.execute_batch(
            r#"CREATE TABLE s (id INTEGER PRIMARY KEY, meta TEXT);
             INSERT INTO s VALUES (1,'{"device":"phone","geo":{"city":"London"}}');"#,
        )
        .unwrap();
    }
    let opts = OpenOpts {
        no_graft: true,
        ..OpenOpts::default()
    };
    let a = open_target(path.to_str().unwrap(), &opts)
        .expect("mount")
        .adapter;
    let a = Dyn(a);
    // The column stays the server's own scalar: no inner arbor,
    // the text intact.
    assert!(run_q(&a, "/s/1/meta/geo/city::").is_empty());
    assert_eq!(
        run_q(&a, "/s/1/meta::"),
        [r#"{"device":"phone","geo":{"city":"London"}}"#]
    );
}

#[test]
fn no_graft_refuses_code_prefix() {
    let dir = std::env::temp_dir().join("qua-mount-no-graft-code-test");
    std::fs::create_dir_all(&dir).unwrap();
    let target = format!("code:{}", dir.display());
    let opts = OpenOpts {
        no_graft: true,
        ..OpenOpts::default()
    };
    let err = match open_target(&target, &opts) {
        Err(e) => e,
        Ok(_) => panic!("must refuse"),
    };
    assert!(err.to_string().contains("code:"), "unexpected error: {err}");
}