quarb-session 0.11.0

Backend-agnostic interactive Quarb session — macro history (&N/&N!/&N#) over a pluggable Executor and Store
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
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
//! Opening a source into a queryable adapter, and running queries
//! against it.
//!
//! `AstAdapter` is object-safe, but each adapter's *render* method
//! (`pointer` / `locator` / `path`) is an inherent method, not on the
//! trait — so, as the Python bindings do, we hold one of a fixed set
//! of adapter families in an enum and dispatch render (and the
//! `WithNow`/`AllowShell` query wrap) by variant.
//!
//! The text-format variants always compile (they are wasm-safe); the
//! native fleet (filesystem, git, SQLite, archives, spreadsheets,
//! source code, mounts) is gated behind the `native` feature, as is
//! the filesystem `open`/`mount` dispatch. The wasm build drives
//! everything through [`Doc::parse`].

use anyhow::{Context, Result, bail};
use quarb::{AllowShell, NodeId, QueryResult, WithNow};

#[cfg(feature = "native")]
use std::path::Path;
use std::rc::Rc;

/// Options that shape how native sources open (unused on wasm, which
/// only parses text).
#[derive(Clone, Copy, Default)]
pub struct Options {
    pub hidden: bool,
    pub respect_ignore: bool,
    pub descend: bool,
}

/// A materialized source: one variant per adapter family. JSON-model
/// formats (json/yaml/toml) render node results as pointers, the rest
/// as locators.
pub enum Doc {
    Json(quarb_json::JsonAdapter),
    Csv(quarb_csv::CsvAdapter),
    Xml(quarb_xml::XmlAdapter),
    Html(quarb_html::HtmlAdapter),
    Sqlite(quarb_sqlite::SqliteAdapter),
    #[cfg(feature = "native")]
    Fs(quarb_fs::FsAdapter),
    #[cfg(feature = "native")]
    FsDeep(quarb_compose::ComposeAdapter<quarb_fs::FsAdapter>),
    #[cfg(feature = "native")]
    Git(quarb_git::GitAdapter),
    #[cfg(feature = "native")]
    Archive(quarb_compose::ComposeAdapter<quarb_archive::ArchiveAdapter>),
    #[cfg(feature = "native")]
    Xlsx(quarb_xlsx::XlsxAdapter),
    #[cfg(feature = "native")]
    Code(quarb_code::CodeAdapter),
    Mount(quarb_mount::MountAdapter),
    /// Any adapter behind the object-safe trait, with its locator
    /// renderer — the carrier for scheme targets opened through
    /// qua's dispatch (`gcl:`, `kafka:`, `neo4j://`, …).
    #[cfg(feature = "native")]
    Boxed(Dyn, Box<dyn Fn(NodeId) -> String>),
}

/// A boxed adapter as an adapter — plain delegation (the
/// quarb-py `Dyn` pattern).
#[cfg(feature = "native")]
pub struct Dyn(pub Box<dyn quarb::AstAdapter>);

#[cfg(feature = "native")]
impl quarb::AstAdapter for Dyn {
    fn root(&self) -> NodeId {
        self.0.root()
    }
    fn children(&self, node: NodeId) -> Vec<NodeId> {
        self.0.children(node)
    }
    fn name(&self, node: NodeId) -> Option<String> {
        self.0.name(node)
    }
    fn parent(&self, node: NodeId) -> Option<NodeId> {
        self.0.parent(node)
    }
    fn traits(&self, node: NodeId) -> Vec<String> {
        self.0.traits(node)
    }
    fn property(&self, node: NodeId, name: &str) -> Option<quarb::Value> {
        self.0.property(node, name)
    }
    fn children_named(&self, node: NodeId, name: &str) -> Vec<NodeId> {
        self.0.children_named(node, name)
    }
    fn default_value(&self, node: NodeId) -> Option<quarb::Value> {
        self.0.default_value(node)
    }
    fn metadata(&self, node: NodeId, key: &str) -> Option<quarb::Value> {
        self.0.metadata(node, key)
    }
    fn links(&self, node: NodeId) -> Vec<(String, NodeId)> {
        self.0.links(node)
    }
    fn backlinks(&self, node: NodeId) -> Vec<(String, NodeId)> {
        self.0.backlinks(node)
    }
    fn resolve(&self, node: NodeId, property: &str, hint: Option<&str>) -> Option<NodeId> {
        self.0.resolve(node, property, hint)
    }
    fn link_property(
        &self,
        source: NodeId,
        label: &str,
        target: NodeId,
        name: &str,
    ) -> Option<quarb::Value> {
        self.0.link_property(source, label, target, name)
    }
    fn quantifier_bound(&self) -> usize {
        self.0.quantifier_bound()
    }
    fn invocation_instant(&self) -> Option<(i64, u32)> {
        self.0.invocation_instant()
    }
    fn unit_scale(&self, expr: &str) -> Option<(f64, String)> {
        self.0.unit_scale(expr)
    }
}

impl Doc {
    /// Parse a text document by format name — the wasm entry point,
    /// and the text tail of the native `open`. Formats: json, yaml,
    /// toml, csv, tsv, xml, html, markdown, jsonl/ndjson.
    pub fn parse(input: &str, format: &str) -> Result<Doc> {
        match format {
            "json" => quarb_json::JsonAdapter::parse(input)
                .map(Doc::Json)
                .context("parsing JSON"),
            "jsonl" | "ndjson" => quarb_json::JsonAdapter::parse_lines(input)
                .map(Doc::Json)
                .context("parsing JSONL"),
            "yaml" | "yml" => quarb_yaml::parse(input).map(Doc::Json).context("parsing YAML"),
            "toml" => quarb_toml::parse(input).map(Doc::Json).context("parsing TOML"),
            "csv" => quarb_csv::CsvAdapter::parse_with_delimiter(input, b',')
                .map(Doc::Csv)
                .context("parsing CSV"),
            "tsv" => quarb_csv::CsvAdapter::parse_with_delimiter(input, b'\t')
                .map(Doc::Csv)
                .context("parsing TSV"),
            "xml" => quarb_xml::XmlAdapter::parse(input)
                .map(Doc::Xml)
                .context("parsing XML"),
            "html" => Ok(Doc::Html(quarb_html::HtmlAdapter::parse(input))),
            "markdown" | "md" => Ok(Doc::Html(quarb_markdown::parse(input))),
            other => bail!("unknown format: {other}"),
        }
    }

    /// Run one query against this source with the session's invocation
    /// instant and shell permission. The query text carries any macro
    /// definitions inline (the session prepends its table), which
    /// `quarb::run` expands.
    pub fn run(&self, query: &str, now: (i64, u32), allow_shell: bool) -> quarb::Result<QueryResult> {
        let (secs, nanos) = now;
        macro_rules! go {
            ($a:expr) => {{
                let nowed = WithNow {
                    inner: $a,
                    secs,
                    nanos,
                };
                if allow_shell {
                    quarb::run(query, &AllowShell { inner: &nowed })
                } else {
                    quarb::run(query, &nowed)
                }
            }};
        }
        match self {
            Doc::Json(a) => go!(a),
            Doc::Csv(a) => go!(a),
            Doc::Xml(a) => go!(a),
            Doc::Html(a) => go!(a),
            Doc::Sqlite(a) => go!(a),
            #[cfg(feature = "native")]
            Doc::Fs(a) => go!(a),
            #[cfg(feature = "native")]
            Doc::FsDeep(a) => go!(a),
            #[cfg(feature = "native")]
            Doc::Git(a) => go!(a),
            #[cfg(feature = "native")]
            Doc::Archive(a) => go!(a),
            #[cfg(feature = "native")]
            Doc::Xlsx(a) => go!(a),
            #[cfg(feature = "native")]
            Doc::Code(a) => go!(a),
            Doc::Mount(a) => go!(a),
            #[cfg(feature = "native")]
            Doc::Boxed(a, _) => go!(a),
        }
    }

    /// Render a node result as its source-appropriate locator.
    pub fn render(&self, node: NodeId) -> String {
        match self {
            Doc::Json(a) => a.pointer(node),
            Doc::Csv(a) => a.locator(node),
            Doc::Xml(a) => a.locator(node),
            Doc::Html(a) => a.locator(node),
            Doc::Sqlite(a) => a.locator(node),
            #[cfg(feature = "native")]
            Doc::Fs(a) => a.path(node).display().to_string(),
            #[cfg(feature = "native")]
            Doc::FsDeep(a) => a.locator(node, |o| a.outer().path(o).display().to_string()),
            #[cfg(feature = "native")]
            Doc::Git(a) => a.locator(node),
            #[cfg(feature = "native")]
            Doc::Archive(a) => a.locator(node, |o| a.outer().locator(o)),
            #[cfg(feature = "native")]
            Doc::Xlsx(a) => a.locator(node),
            #[cfg(feature = "native")]
            Doc::Code(a) => a.locator(node),
            Doc::Mount(a) => generic_locator(a, node),
            #[cfg(feature = "native")]
            Doc::Boxed(_, render) => render(node),
        }
    }

    /// Open a SQLite database from its file bytes — a `.db` that
    /// never touched a filesystem (the browser's uploaded files).
    pub fn sqlite_bytes(bytes: &[u8]) -> Result<Doc> {
        Ok(Doc::Sqlite(
            quarb_sqlite::SqliteAdapter::from_bytes(bytes)
                .map_err(|e| anyhow::anyhow!("{e}"))
                .context("opening SQLite bytes")?,
        ))
    }

    /// Mount already-built documents as named children of one root —
    /// the general wasm-safe mount, for callers that assembled their
    /// `Doc`s from text or bytes rather than paths.
    pub fn mount_docs(parts: Vec<(String, Doc)>) -> Result<Doc> {
        let mut mounts: Vec<quarb_mount::Mount> = Vec::new();
        for (name, doc) in parts {
            if mounts.iter().any(|m| m.name == name) {
                bail!("two sources mount as '{name}'; give each a distinct name");
            }
            mounts.push(quarb_mount::Mount {
                name,
                adapter: doc.into_boxed()?,
            });
        }
        Ok(Doc::Mount(quarb_mount::MountAdapter::new(mounts)))
    }

    /// Mount several already-parsed text documents as named children
    /// of one root — [`Doc::mount_docs`] over [`Doc::parse`], for
    /// callers that hold text (the browser playground's paste
    /// boxes). `parts` is `(name, format, text)`.
    pub fn mount_texts(parts: &[(String, String, String)]) -> Result<Doc> {
        let mut docs: Vec<(String, Doc)> = Vec::new();
        for (name, format, text) in parts {
            let doc = Doc::parse(text, format)
                .with_context(|| format!("parsing '{name}' as {format}"))?;
            docs.push((name.clone(), doc));
        }
        Doc::mount_docs(docs)
    }

    /// Box this source as a shared adapter — a mount child.
    fn into_boxed(self) -> Result<Box<dyn quarb::AstAdapter>> {
        use quarb_mount::Shared;
        Ok(match self {
            Doc::Json(a) => Box::new(Shared(Rc::new(a))),
            Doc::Csv(a) => Box::new(Shared(Rc::new(a))),
            Doc::Xml(a) => Box::new(Shared(Rc::new(a))),
            Doc::Html(a) => Box::new(Shared(Rc::new(a))),
            Doc::Sqlite(a) => Box::new(Shared(Rc::new(a))),
            #[cfg(feature = "native")]
            Doc::Fs(a) => Box::new(Shared(Rc::new(a))),
            #[cfg(feature = "native")]
            Doc::FsDeep(a) => Box::new(Shared(Rc::new(a))),
            #[cfg(feature = "native")]
            Doc::Git(a) => Box::new(Shared(Rc::new(a))),
            #[cfg(feature = "native")]
            Doc::Archive(a) => Box::new(Shared(Rc::new(a))),
            #[cfg(feature = "native")]
            Doc::Xlsx(a) => Box::new(Shared(Rc::new(a))),
            #[cfg(feature = "native")]
            Doc::Code(a) => Box::new(Shared(Rc::new(a))),
            Doc::Mount(_) => bail!("cannot nest a mount inside a mount"),
            #[cfg(feature = "native")]
            Doc::Boxed(a, _) => a.0,
        })
    }
}

// ---------------------------------------------------------------------
// Native-only: filesystem/db/git dispatch and multi-source mounts.
// ---------------------------------------------------------------------

#[cfg(feature = "native")]
impl Doc {
    /// Open one path as a local source. Directories are filesystem
    /// trees (`--descend` grafts parseable leaves); `git:PATH` opens a
    /// repository; binary kinds (SQLite, spreadsheets, archives) and
    /// source files dispatch by extension/magic; everything else is a
    /// text document parsed by extension or content sniff.
    pub fn open(path: &Path, opts: &Options) -> Result<Doc> {
        if path.is_dir() {
            let fsopts = quarb_fs::FsOptions {
                hidden: opts.hidden,
                respect_ignore: opts.respect_ignore,
            };
            let fs = quarb_fs::FsAdapter::with_options(path, fsopts)
                .with_context(|| format!("opening directory {}", path.display()))?;
            return Ok(if opts.descend {
                Doc::FsDeep(quarb_compose::ComposeAdapter::with_source_paths(
                    fs,
                    |fs, n| Some(fs.path(n)),
                ))
            } else {
                Doc::Fs(fs)
            });
        }

        let s = path.to_string_lossy();
        if let Some(repo) = s.strip_prefix("git:") {
            let a =
                quarb_git::GitAdapter::open(Path::new(repo)).context("opening git repository")?;
            return Ok(Doc::Git(a));
        }

        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase());

        if let Some(e) = &ext
            && quarb_code::supported(e)
        {
            let a = quarb_code::CodeAdapter::open(path).context("parsing source file")?;
            return Ok(Doc::Code(a));
        }
        if matches!(ext.as_deref(), Some("xlsx" | "xls" | "ods")) {
            let a = quarb_xlsx::XlsxAdapter::open(path).context("opening workbook")?;
            return Ok(Doc::Xlsx(a));
        }
        if is_sqlite(path) {
            let a = quarb_sqlite::SqliteAdapter::open(path).context("opening SQLite database")?;
            return Ok(Doc::Sqlite(a));
        }
        if is_archive(path) {
            let a = quarb_archive::ArchiveAdapter::open(path).context("opening archive")?;
            return Ok(Doc::Archive(quarb_compose::ComposeAdapter::new(a)));
        }

        // Text documents.
        let text = std::fs::read_to_string(path)
            .with_context(|| format!("reading {}", path.display()))?;
        let text = text
            .strip_prefix('\u{feff}')
            .map(str::to_owned)
            .unwrap_or(text);
        match ext.as_deref() {
            Some("csv") => Doc::parse(&text, "csv"),
            Some("tsv") => Doc::parse(&text, "tsv"),
            Some("yaml" | "yml") => Doc::parse(&text, "yaml"),
            Some("toml") => Doc::parse(&text, "toml"),
            Some("md" | "markdown") => Doc::parse(&text, "markdown"),
            Some("jsonl" | "ndjson") => Doc::parse(&text, "jsonl"),
            _ => {
                if is_xml(path, &text) {
                    Doc::parse(&text, "xml")
                } else if is_html(path, &text) {
                    Doc::parse(&text, "html")
                } else {
                    Doc::parse(&text, "json")
                }
            }
        }
    }

    /// Open several sources as named children of one root (file stem =
    /// mount name), so a single query — including a `<=>` join — spans
    /// them all.
    pub fn mount(paths: &[std::path::PathBuf], opts: &Options) -> Result<Doc> {
        let specs: Vec<crate::MountSpec> = paths
            .iter()
            .map(|p| crate::MountSpec {
                name: None,
                path: p.clone(),
            })
            .collect();
        Doc::mount_specs(&specs, opts)
    }

    /// [`Doc::mount`] with optional explicit mount names
    /// (`NAME=TARGET`); an unnamed spec mounts under its file stem.
    pub fn mount_specs(specs: &[crate::MountSpec], opts: &Options) -> Result<Doc> {
        let mut mounts: Vec<quarb_mount::Mount> = Vec::new();
        for (i, spec) in specs.iter().enumerate() {
            let name = spec.name.clone().unwrap_or_else(|| {
                spec.path
                    .file_stem()
                    .map(|s| s.to_string_lossy().into_owned())
                    .unwrap_or_else(|| format!("doc{i}"))
            });
            if mounts.iter().any(|m| m.name == name) {
                bail!(
                    "input '{}' mounts as '{name}', colliding with an earlier input of the \
                     same name; give each a distinct basename (or a NAME=TARGET alias)",
                    spec.path.display()
                );
            }
            let adapter = Doc::open(&spec.path, opts)?.into_boxed()?;
            mounts.push(quarb_mount::Mount { name, adapter });
        }
        Ok(Doc::Mount(quarb_mount::MountAdapter::new(mounts)))
    }

}

/// A name-path locator built from the adapter trait alone
/// (`parent`/`name`) — used for a mount, whose per-source render
/// functions we do not keep.
fn generic_locator<A: quarb::AstAdapter>(a: &A, node: NodeId) -> String {
    let mut parts = Vec::new();
    let mut cur = Some(node);
    while let Some(n) = cur {
        if let Some(nm) = a.name(n) {
            parts.push(nm);
        }
        cur = a.parent(n);
    }
    parts.reverse();
    format!("/{}", parts.join("/"))
}

/// Whether a file is a SQLite database — by extension, or the 16-byte
/// header magic.
#[cfg(feature = "native")]
fn is_sqlite(path: &Path) -> bool {
    if path
        .extension()
        .and_then(|e| e.to_str())
        .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "db" | "sqlite" | "sqlite3"))
    {
        return true;
    }
    use std::io::Read as _;
    let mut buf = [0u8; 16];
    std::fs::File::open(path)
        .and_then(|mut f| f.read_exact(&mut buf))
        .is_ok()
        && &buf == b"SQLite format 3\0"
}

/// Whether a file is an archive — by extension, or zip/gzip magic.
#[cfg(feature = "native")]
fn is_archive(path: &Path) -> bool {
    if path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
        matches!(
            e.to_ascii_lowercase().as_str(),
            "zip" | "tar" | "gz" | "tgz" | "jar" | "war" | "docx" | "pptx" | "odt" | "odp"
        )
    }) {
        return true;
    }
    use std::io::Read as _;
    let mut buf = [0u8; 2];
    std::fs::File::open(path)
        .and_then(|mut f| f.read_exact(&mut buf))
        .is_ok()
        && (&buf == b"PK" || buf == [0x1f, 0x8b])
}

/// Whether to parse as XML: an `.xml`/`.svg`/`.xhtml` name, or a
/// `<?xml` prolog.
#[cfg(feature = "native")]
fn is_xml(path: &Path, text: &str) -> bool {
    path.extension()
        .and_then(|e| e.to_str())
        .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "xml" | "svg" | "xhtml"))
        || text.trim_start().starts_with("<?xml")
}

/// Whether to parse as HTML: an `.html`/`.htm` name, or content that
/// starts with `<`.
#[cfg(feature = "native")]
fn is_html(path: &Path, text: &str) -> bool {
    path.extension()
        .and_then(|e| e.to_str())
        .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "html" | "htm"))
        || text.trim_start().starts_with('<')
}