Skip to main content

omgbase_surface/
context.rs

1//! The query binding (`spec/surface/README.md` §1): a [`DataContext`] over
2//! the store, so the `oqx` in-memory engine reproduces the whole OQX surface
3//! — roots, intrinsics, reach-through, structural relations, the edge graph,
4//! the row functions — without a bespoke compiler. Port of
5//! `packages/core/src/oqx-js/context.ts`.
6//!
7//! Rows are the store's raw column objects (blobs as hex) carrying a hidden
8//! tag column ([`TAG_KEY`]) naming their target; `get` routes field /
9//! attribute / relation resolution per target, lazily querying the store.
10//! Row functions (`text`, `under`, …) arrive as methods on the `$self`
11//! receiver (see the runner's AST rewrite), since a free function sees no row.
12//!
13//! The tier-3 planner ([`crate::planner`]) hands the rows its SQL produced
14//! back through [`StoreContext::with_rows_root`]: the context then serves them
15//! as the residual query's [`oqx::ROWS_ROOT`] scan, while every other root,
16//! relation, intrinsic and row function still reaches the store — the
17//! reference's `rowsRoot` context option.
18//!
19//! Errors travel the engine's channel: a failure inside a property read or a
20//! row function — a bare target name, a store failure — is the
21//! `Err` of `get` / `call_method` (an eval-stage [`OqxError`], since `oqx`
22//! 0.13), which aborts the run exactly like a throw from the reference's
23//! `get`; the runner maps it to `filter_invalid` with the same message. The
24//! one seam still without a channel is `root` (the engine reads a named root
25//! for the top-level source and for a caret that reaches the root scope), so
26//! a store failure during a root scan is kept in [`StoreContext::take_root_failure`]
27//! and the runner reports it after the run.
28//!
29//! One seam differs from the reference and is bridged here:
30//!
31//! * the Rust engine expands `entries(x)` in row position itself (never via
32//!   `call_function`), so the `data` / `frontmatter` / `inline` source
33//!   handles are materialized eagerly as plain objects — one key per
34//!   top-level property in key order, valued by the scalar-vs-list rule —
35//!   instead of the reference's lazy handle. `frontmatter.<k>` and
36//!   `entries(frontmatter)` read the same values either way.
37
38use std::cell::{Cell, RefCell};
39use std::collections::HashMap;
40use std::rc::Rc;
41
42use omgbase_properties::Bound;
43use omgbase_search::{cosine_bytes, sanitize_fts_query};
44use oqx::semantics::{builtin_function, builtin_method_with, make_range, string_form};
45use oqx::{
46    CompiledRegex, DataContext, Object, OqxError, RegexDialect, RowIndex, Value, compile_regex,
47};
48use rusqlite::types::{Value as SqlValue, ValueRef};
49use rusqlite::{Connection, OptionalExtension, params_from_iter};
50
51use crate::paths::{reference_path, storage_path};
52use crate::planner;
53
54/// The hidden column tagging a store row with its target.
55pub const TAG_KEY: &str = "__oqx_target";
56/// The key of a lazy ROOT SCAN marker: `{ "__oqx_scan": "docs" }` stands for
57/// `^docs` / a bare `docs` at the root until the engine reads it in row position
58/// (`to_rows`) or is about to observe it as a value (`materialize` — an
59/// operand, an argument, a projected item, a key), or probes it through
60/// `index_for`, in which case the scan never runs. The marker never reaches
61/// the language: the engine materializes every value it observes, so `==`,
62/// `in`, `entries(…)`, `size(…)`, truthiness, `distinct` and `order by` see
63/// the rows exactly as the reference's `Proxy` array shows them. A `Value` has
64/// no identity or laziness of its own, so this is the port of that handle.
65pub const SCAN_KEY: &str = "__oqx_scan";
66
67/// The five root collections (`spec/surface` §1.1): the four live row kinds
68/// and, since 4.7, `revisions` — the history target, one row per revision of
69/// the repository's documents (the `revisions` × `commits` join). The
70/// reference splits the name in two (`Target`, the four kinds its planner
71/// pushes down and its unknown-names pass first keyed by; `Kind`/`Root`, all
72/// five); here one enum tags every row, and the planner declines the fifth
73/// (`crate::planner::root_target` is five-wide, `compile` plans four).
74#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
75pub enum Target {
76    Docs,
77    Blocks,
78    Nodes,
79    Links,
80    Revisions,
81}
82
83impl Target {
84    /// The root name: `docs` | `blocks` | `nodes` | `links` | `revisions`.
85    #[must_use]
86    pub fn as_str(self) -> &'static str {
87        match self {
88            Target::Docs => "docs",
89            Target::Blocks => "blocks",
90            Target::Nodes => "nodes",
91            Target::Links => "links",
92            Target::Revisions => "revisions",
93        }
94    }
95
96    /// The target a root name denotes, if any.
97    #[must_use]
98    pub fn parse(s: &str) -> Option<Self> {
99        Some(match s {
100            "docs" => Target::Docs,
101            "blocks" => Target::Blocks,
102            "nodes" => Target::Nodes,
103            "links" => Target::Links,
104            "revisions" => Target::Revisions,
105            _ => return None,
106        })
107    }
108
109    /// The plural noun of the kind's rows, as the root-row messages spell it
110    /// (`crate::query`: "the repository's documents").
111    #[must_use]
112    pub fn noun(self) -> &'static str {
113        match self {
114            Target::Docs => "documents",
115            Target::Blocks => "blocks",
116            Target::Nodes => "nodes",
117            Target::Links => "links",
118            Target::Revisions => "revisions",
119        }
120    }
121}
122
123/// THE NAME RULE (`spec/surface` §1.2, 3.0). `$` belongs to OQX: `$it`,
124/// `$key`, `$depth`, `$stop`, `$leaf`, `$frontier`, `$ordinal` are values the
125/// LANGUAGE injects into a scope; omgbase adds no `$` names. Every engine
126/// attribute is a bare snake_case name that WINS on collision — the convention
127/// the relations (`children`, `blocks`, `out_links`, `doc`, `frontmatter`, …)
128/// always followed: a bare name that is an engine attribute reads the
129/// engine's value, never the author's. The attributes: every row's
130/// `id`/`path`; docs' and blocks' `raw`/`hash`/`updated_at`; docs' `title`
131/// (the computed title) and `tags` (authored tags ∪ body hashtags) and
132/// `format`; a foreign key named for what it is (`doc_id`, `block_id`,
133/// `via_id`, `dst_id`, `dst_path`, `uri`), a column its column (`type`,
134/// `text`, `depth`, `ordinal`, `kind`, `predicate`, `field`). User data is
135/// bare too, read by any non-colliding key; where it collides it is reached
136/// through a source handle — `data` (the merged authored view: frontmatter +
137/// inline by the property rule, exactly the read a bare non-colliding key
138/// performs), `frontmatter`, `inline` — so `data.path` is the author's `path:`
139/// key, `data.tags` the authored list alone, `data.title` the authored title.
140/// There is no loud-error set: a bare `id`/`path`/`updated_at`/`hash`/`raw`
141/// is simply the engine's attribute (before this batch of 3.0 the attributes
142/// were `$`-prefixed and the bare spelling was an error, §9). A bare target
143/// name — `docs`, `links`, … — is a loud error of its own (`crate::query`).
144const DOC_ATTRIBUTES: [&str; 8] = [
145    "id",
146    "path",
147    "raw",
148    "hash",
149    "updated_at",
150    "title",
151    "tags",
152    "format",
153];
154const BLOCK_ATTRIBUTES: [&str; 11] = [
155    "id",
156    "path",
157    "raw",
158    "hash",
159    "updated_at",
160    "doc_id",
161    "type",
162    "text",
163    "attrs",
164    "depth",
165    "ordinal",
166];
167const NODE_ATTRIBUTES: [&str; 8] = [
168    "id", "path", "doc_id", "block_id", "kind", "name", "value", "attrs",
169];
170const EDGE_ATTRIBUTES: [&str; 13] = [
171    "id",
172    "path",
173    "doc_id",
174    "block_id",
175    "via_id",
176    "dst_id",
177    "dst_path",
178    "uri",
179    "field",
180    "dst_kind",
181    "predicate",
182    "provenance",
183    "anchor",
184];
185/// The history target (`spec/surface` §1.2, 4.7): a revision row's own
186/// columns under the names `docs_history` already uses (`rev`, `seq`,
187/// `commit`, `origin`, `actor`, `hash`), the commit's `ts` and `reason`, and
188/// `is_current`.
189const REVISION_ATTRIBUTES: [&str; 12] = [
190    "id",
191    "path",
192    "rev",
193    "seq",
194    "doc_id",
195    "commit",
196    "ts",
197    "origin",
198    "actor",
199    "reason",
200    "hash",
201    "is_current",
202];
203/// The engine attributes per kind (`spec/surface` §1.2 table).
204#[must_use]
205pub fn attributes(t: Target) -> &'static [&'static str] {
206    match t {
207        Target::Docs => &DOC_ATTRIBUTES,
208        Target::Blocks => &BLOCK_ATTRIBUTES,
209        Target::Nodes => &NODE_ATTRIBUTES,
210        Target::Links => &EDGE_ATTRIBUTES,
211        Target::Revisions => &REVISION_ATTRIBUTES,
212    }
213}
214
215/// The revisions scan (`spec/surface` §1.1, 4.7): every revision of every
216/// document of the repository — tombstoned documents included, history is
217/// history — with its commit. The `revisions` table carries no `repo_id`, so
218/// the repository guard joins `docs`. `is_current` is `docs_history`'s
219/// `isCurrent`: the revision is the document's `current_rev`. The planner's
220/// clauses for the kind ([`crate::planner::columns`], `from_clause`) are
221/// these same strings.
222pub(crate) const REVISION_COLS: &str = "r.rev_id, r.doc_id, r.seq, r.rendered_hash, r.path, r.commit_id, c.ts, c.origin, c.actor, c.reason, (d.current_rev = r.rev_id) AS is_current";
223pub(crate) const REVISION_FROM: &str =
224    "revisions r JOIN docs d ON d.doc_id = r.doc_id JOIN commits c ON c.commit_id = r.commit_id";
225/// The source handles of a document (§1.2): `data` is the merged authored
226/// view (frontmatter + inline), the other two one source each.
227pub const SOURCE_HANDLES: [&str; 3] = ["data", "frontmatter", "inline"];
228
229/// The key marking a LAZY OWNER row (foreign-key elimination, `spec/surface`
230/// §1, 3.0): the owner a reach-through hands out (`doc` on a block, node or
231/// edge; `block` on a node) carries only the columns the child row already
232/// knows — `doc_id` + `path` (from the child's `doc_id`/`src_doc` and
233/// `__path`), or `block_id` + `doc_id` + `__path` — tagged with the owner's
234/// target, plus this key. `get` answers `id`, `path`, the owner's own
235/// foreign keys, its relations and its properties (which need only the id)
236/// from those columns and runs NO statement, exactly like the bare `doc_id`;
237/// the first read of anything else (`format`, `hash`, `text`, …) loads the
238/// full row ([`StoreContext::owner_full`], memoized per run). The port of the
239/// reference's `lazyOwner` Proxy. The marker is a tagged row to everything
240/// else (`identity`, `render_row_values`, `materialize`, hits) and the hidden
241/// key is stripped with the tag.
242pub const LAZY_KEY: &str = "__oqx_lazy";
243
244/// The value of a statically SINGLE relation that has no row — `dst` on an
245/// external or dangling link, `block` on a node without one (oqx 0.20,
246/// SEMANTICS §3): an object the engine treats as one row with no rows
247/// (`to_rows` empty, `is_single` true), so `dst { title }` is absent rather
248/// than `[]`, while as a VALUE it is absent (`materialize`), so `dst == null`,
249/// `has(dst)` and `dst.title` read as before. The port of the reference's
250/// `ABSENT_SINGLE`.
251pub const ABSENT_KEY: &str = "__oqx_absent";
252
253fn absent_single() -> Value {
254    let mut o = Object::with_capacity(1);
255    o.insert(ABSENT_KEY, Value::Bool(true));
256    Value::Object(o)
257}
258
259/// Whether `v` is the absent-single marker.
260fn is_absent_single(v: &Value) -> bool {
261    v.as_object()
262        .is_some_and(|o| o.len() == 1 && o.contains_key(ABSENT_KEY))
263}
264
265/// A query phrase's embedding: the model whose cache to read and the vector
266/// as a float32 little-endian blob.
267#[derive(Clone, Debug, PartialEq)]
268pub struct SemanticVec {
269    pub model: String,
270    pub vec: Vec<u8>,
271}
272
273/// The store-backed context for one repo.
274pub struct StoreContext<'a> {
275    conn: &'a Connection,
276    repo_id: String,
277    semantic: HashMap<String, SemanticVec>,
278    /// A store failure inside [`DataContext::root`], the one read the
279    /// engine's seam cannot fail through (see the module doc).
280    root_failure: RefCell<Option<OqxError>>,
281    /// The rows a tier-3 plan produced, served as [`oqx::ROWS_ROOT`].
282    rows_root: Option<RowsRoot>,
283    /// `matches()` patterns compiled during this run, by `(String(pattern),
284    /// flags)`; see [`Self::matches_memoized`].
285    regexes: RefCell<HashMap<(String, Option<String>), CompiledRegex>>,
286    /// Root scans read during this run, by target: a context lives for one
287    /// run, during which the store does not change, so `^docs` read from
288    /// every outer row is one SELECT, not one per row.
289    scans: RefCell<HashMap<Target, Rc<Vec<Value>>>>,
290    /// How many root scans actually ran (tests prove a probe runs none).
291    scans_run: Cell<usize>,
292    /// How many statements this context has run in all (`all` / `exists`),
293    /// so a test can prove a reach-through to the owner's identity runs none.
294    statements_run: Cell<usize>,
295    /// Lazy owners loaded in full during this run, by `(target, id)` — the
296    /// store does not change within a run, so an owner is read at most once.
297    owners: RefCell<HashMap<(Target, String), Option<Value>>>,
298}
299
300/// The planned rows behind [`oqx::ROWS_ROOT`]: cloned out on every read, or
301/// — when the runner has proven the residual reads the root exactly once —
302/// moved out on the first read (`once`), which spares one deep copy and one
303/// drop of every produced row.
304struct RowsRoot {
305    rows: RefCell<Option<Vec<Value>>>,
306    once: bool,
307}
308
309fn sql_value(v: ValueRef<'_>) -> Value {
310    match v {
311        ValueRef::Null => Value::Null,
312        ValueRef::Integer(i) => Value::Number(i as f64),
313        ValueRef::Real(f) => Value::Number(f),
314        ValueRef::Text(t) => Value::Str(String::from_utf8_lossy(t).into_owned()),
315        ValueRef::Blob(b) => Value::Str(omgbase_format::hash::hex(b)),
316    }
317}
318
319/// A [`Value`] as a SQL parameter (`has_edge`'s destination, the planner's
320/// bound operands): booleans as 1/0 — how `json_extract` surfaces JSON
321/// booleans, so `attrs.b == true` compares against `1` — numbers as REAL
322/// (a JavaScript number binds as a double), absent as NULL.
323pub(crate) fn to_sql(v: &Value) -> SqlValue {
324    match v {
325        Value::Undefined | Value::Null | Value::Range(_) => SqlValue::Null,
326        Value::Bool(b) => SqlValue::Integer(i64::from(*b)),
327        Value::Number(n) => SqlValue::Real(*n),
328        Value::Str(s) => SqlValue::Text(s.clone()),
329        Value::Array(_) | Value::Object(_) => SqlValue::Text(v.to_string()),
330    }
331}
332
333/// JavaScript `String(v)` of an argument.
334fn js_string(v: &Value) -> String {
335    v.to_string()
336}
337
338/// `String(args[0] ?? "")`.
339fn arg_or_empty(args: &[Value], i: usize) -> String {
340    match args.get(i) {
341        None | Some(Value::Undefined) | Some(Value::Null) => String::new(),
342        Some(v) => js_string(v),
343    }
344}
345
346/// `JSON.parse` when a string, else the value (`null` → absent).
347fn parse_json(v: &Value) -> Value {
348    match v {
349        Value::Str(s) => {
350            serde_json::from_str::<serde_json::Value>(s).map_or_else(|_| v.clone(), Value::from)
351        }
352        Value::Null | Value::Undefined => Value::Undefined,
353        other => other.clone(),
354    }
355}
356
357/// A store failure as the engine's eval error (the message the reference's
358/// raw exception would carry).
359fn sql_err(e: rusqlite::Error) -> OqxError {
360    OqxError::eval(format!("sqlite: {e}"))
361}
362
363/// The tag of a store row, if it is one.
364pub fn target_of(row: &Value) -> Option<Target> {
365    row.as_object()
366        .and_then(|o| o.get(TAG_KEY))
367        .and_then(Value::as_str)
368        .and_then(Target::parse)
369}
370
371/// Whether `row` is a lazy owner (see [`LAZY_KEY`]).
372fn is_lazy_owner(row: &Value) -> bool {
373    row.as_object().is_some_and(|o| o.contains_key(LAZY_KEY))
374}
375
376/// The target of a lazy root-scan marker, if `v` is one.
377#[must_use]
378pub fn scan_of(v: &Value) -> Option<Target> {
379    v.as_object()
380        .and_then(|o| o.get(SCAN_KEY))
381        .and_then(Value::as_str)
382        .and_then(Target::parse)
383}
384
385fn scan_marker(t: Target) -> Value {
386    let mut o = Object::with_capacity(1);
387    o.insert(SCAN_KEY, Value::Str(t.as_str().to_owned()));
388    Value::Object(o)
389}
390
391/// The five root collections, in the order the root object lists them
392/// (`spec/surface` §1.1; `revisions` the fifth since 4.7).
393pub const ALL_TARGETS: [Target; 5] = [
394    Target::Docs,
395    Target::Blocks,
396    Target::Nodes,
397    Target::Links,
398    Target::Revisions,
399];
400
401/// Whether `row` is the root object ([`StoreContext::root_object`]): a plain
402/// object whose own keys are exactly the five collections, each the lazy
403/// marker of its target. Recognized by shape — a hidden tag would show up in
404/// `entries(^$it)`, which must name exactly the collections.
405fn is_root_object(row: &Value) -> bool {
406    row.as_object().is_some_and(|o| {
407        o.len() == ALL_TARGETS.len()
408            && ALL_TARGETS
409                .iter()
410                .all(|t| o.get(t.as_str()).is_some_and(|v| scan_of(v) == Some(*t)))
411    })
412}
413
414fn col<'v>(row: &'v Value, key: &str) -> &'v Value {
415    row.as_object()
416        .and_then(|o| o.get(key))
417        .unwrap_or(&Value::Undefined)
418}
419
420fn col_str(row: &Value, key: &str) -> String {
421    match col(row, key) {
422        Value::Undefined | Value::Null => String::new(),
423        v => js_string(v),
424    }
425}
426
427/// Strip the hidden tag from a value tree (the wire form never carries it).
428#[must_use]
429pub fn strip_tags(v: Value) -> Value {
430    match v {
431        Value::Object(o) => Value::Object(
432            o.into_iter()
433                .filter(|(k, _)| k != TAG_KEY && k != LAZY_KEY)
434                .map(|(k, x)| (k, strip_tags(x)))
435                .collect(),
436        ),
437        Value::Array(a) => Value::Array(a.into_iter().map(strip_tags).collect()),
438        other => other,
439    }
440}
441
442/// §1.4 rows as values (1.2): a store row that surfaces as a VALUE in a result
443/// tree — a nested `collect { }` / `first { }` / `single { }` with an empty
444/// projection, or a `values` item that is a row — renders as `{ id, path }`
445/// (3.0: the hit envelope's own keys, spelled as the attributes; the target's
446/// id column as a string; the owning document's path in the reference form,
447/// §1 "Paths": a docs row's `path`, every other row's `__path` join column,
448/// rooted), never the store row. Everything else
449/// recurses, dropping the hidden tag as [`strip_tags`].
450#[must_use]
451pub fn render_row_values(v: Value) -> Value {
452    match v {
453        Value::Object(o) => {
454            let row = Value::Object(o);
455            if let Some(t) = target_of(&row) {
456                let (id_col, path_col) = match t {
457                    Target::Docs => ("doc_id", "path"),
458                    Target::Blocks => ("block_id", "__path"),
459                    Target::Nodes => ("node_id", "__path"),
460                    Target::Links => ("edge_id", "__path"),
461                    // a revision's path is `revisions.path` — the path it was
462                    // committed under (a move re-paths the current revision; §1.2, 4.7).
463                    Target::Revisions => ("rev_id", "path"),
464                };
465                let mut out = Object::with_capacity(2);
466                out.insert(crate::query::HIT_ID, Value::Str(col_str(&row, id_col)));
467                let path = match col(&row, path_col) {
468                    Value::Undefined | Value::Null => String::new(),
469                    v => reference_path(&js_string(v)),
470                };
471                out.insert(crate::query::HIT_PATH, Value::Str(path));
472                return Value::Object(out);
473            }
474            let Value::Object(o) = row else {
475                unreachable!()
476            };
477            Value::Object(
478                o.into_iter()
479                    .filter(|(k, _)| k != TAG_KEY && k != LAZY_KEY)
480                    .map(|(k, x)| (k, render_row_values(x)))
481                    .collect(),
482            )
483        }
484        Value::Array(a) => Value::Array(a.into_iter().map(render_row_values).collect()),
485        other => other,
486    }
487}
488
489impl<'a> StoreContext<'a> {
490    /// A context over `conn` scoped to `repo_id`, with the query phrases'
491    /// vectors for `semantic(...)` (empty when no provider ran).
492    #[must_use]
493    pub fn new(
494        conn: &'a Connection,
495        repo_id: &str,
496        semantic: HashMap<String, SemanticVec>,
497    ) -> Self {
498        Self {
499            conn,
500            repo_id: repo_id.to_owned(),
501            semantic,
502            root_failure: RefCell::new(None),
503            rows_root: None,
504            regexes: RefCell::new(HashMap::new()),
505            scans: RefCell::new(HashMap::new()),
506            scans_run: Cell::new(0),
507            statements_run: Cell::new(0),
508            owners: RefCell::new(HashMap::new()),
509        }
510    }
511
512    /// How many statements this context has run (every `SELECT`, the root
513    /// scans included). A reach-through to the owner's identity adds none.
514    #[must_use]
515    pub fn statements_run(&self) -> usize {
516        self.statements_run.get()
517    }
518
519    /// The repository this context is scoped to.
520    #[must_use]
521    pub fn repo_id(&self) -> &str {
522        &self.repo_id
523    }
524
525    /// How many root scans (`SELECT … FROM <target>` whole) this context has
526    /// run — at most one per target per run; none for a block whose probes
527    /// the store indexes answered.
528    #[must_use]
529    pub fn scans_run(&self) -> usize {
530        self.scans_run.get()
531    }
532
533    /// The rows of a root scan, read once per run and shared.
534    pub(crate) fn scan_rows(&self, t: Target) -> oqx::Result<Rc<Vec<Value>>> {
535        if let Some(rows) = self.scans.borrow().get(&t) {
536            return Ok(Rc::clone(rows));
537        }
538        self.scans_run.set(self.scans_run.get() + 1);
539        let rows = match self.root_scan(t)? {
540            Value::Array(rows) => Rc::new(rows),
541            _ => Rc::new(Vec::new()),
542        };
543        self.scans.borrow_mut().insert(t, Rc::clone(&rows));
544        Ok(rows)
545    }
546
547    /// `refs(x)` (`spec/surface` §1.3, 1.5): the live documents the document
548    /// references held in a property name. `x` is a string, a list, or absent;
549    /// every string element that names a live document of this repo — a doc
550    /// id (`d_…`), a repo-root-absolute path (`/a/b.md`) or a bare
551    /// repo-relative path (`a/b.md`) — resolves to that document's row;
552    /// anything else (a dangling reference, a non-string element) is dropped.
553    /// Order preserved, duplicates kept. Port of the reference's `refs`.
554    fn refs(&self, x: &Value) -> oqx::Result<Value> {
555        let items: Vec<&Value> = match x {
556            Value::Undefined | Value::Null => Vec::new(),
557            Value::Array(a) => a.iter().collect(),
558            other => vec![other],
559        };
560        let mut out = Vec::new();
561        for item in items {
562            if let Value::Str(s) = item
563                && let Some(row) = self.ref_doc(s)?
564            {
565                out.push(row);
566            }
567        }
568        Ok(Value::Array(out))
569    }
570
571    /// One document reference resolved: by `path` after stripping one leading
572    /// `/`, else — when it begins with `d_` — by `doc_id`. Each is one indexed
573    /// lookup under the root scan's guards, columns and order
574    /// ([`crate::planner`]), so the row is indistinguishable from a scanned one
575    /// and the docs root is never read.
576    fn ref_doc(&self, r: &str) -> oqx::Result<Option<Value>> {
577        let t = Target::Docs;
578        let lookup = |column: &str, value: &str| -> oqx::Result<Option<Value>> {
579            let sql = format!(
580                "SELECT {} FROM {} WHERE {} AND d.{column} = ? ORDER BY {}",
581                planner::columns(t),
582                planner::from_clause(t),
583                planner::guards(t),
584                planner::order_clause(t)
585            );
586            let params = [
587                SqlValue::Text(self.repo_id.clone()),
588                SqlValue::Text(value.to_owned()),
589            ];
590            Ok(self.one(&sql, &params)?.map(|row| tag_row(row, t)))
591        };
592        if let Some(row) = lookup("path", storage_path(r))? {
593            return Ok(Some(row));
594        }
595        if r.starts_with("d_") {
596            return lookup("doc_id", r);
597        }
598        Ok(None)
599    }
600
601    /// The tagged rows of one store-index probe statement (`store_index`).
602    pub(crate) fn probe_rows(
603        &self,
604        t: Target,
605        sql: &str,
606        params: &[SqlValue],
607    ) -> oqx::Result<Vec<Value>> {
608        Ok(tag_rows(self.all(sql, params)?, t))
609    }
610
611    /// A lazy root-scan marker expanded to its rows (`Err` → recorded as the
612    /// run's root failure, served empty — the `root` discipline).
613    fn expand_scan(&self, t: Target) -> Vec<Value> {
614        match self.scan_rows(t) {
615            Ok(rows) => rows.as_ref().clone(),
616            Err(e) => {
617                let mut slot = self.root_failure.borrow_mut();
618                if slot.is_none() {
619                    *slot = Some(e);
620                }
621                Vec::new()
622            }
623        }
624    }
625
626    /// Serve `rows` — target-tagged store rows a plan produced — as the
627    /// [`oqx::ROWS_ROOT`] scan (the residual query's source). Every other
628    /// root and every relation, intrinsic and row function still hits the
629    /// store, so the residual sees exactly what a full scan would.
630    #[must_use]
631    pub fn with_rows_root(mut self, rows: Vec<Value>) -> Self {
632        self.rows_root = Some(RowsRoot {
633            rows: RefCell::new(Some(rows)),
634            once: false,
635        });
636        self
637    }
638
639    /// [`Self::with_rows_root`] for a residual whose ONLY read of
640    /// [`oqx::ROWS_ROOT`] is its source scan (the runner checks the AST: the
641    /// name appears nowhere else — no `^`-reach, no `limit`/`offset`, no
642    /// nested mention): the rows are moved out on that first read instead
643    /// of deep-copied, and a second read — which cannot happen — would see
644    /// an empty scan. Same results as [`Self::with_rows_root`], one row copy
645    /// and one drop fewer.
646    #[must_use]
647    pub fn with_rows_root_once(mut self, rows: Vec<Value>) -> Self {
648        self.rows_root = Some(RowsRoot {
649            rows: RefCell::new(Some(rows)),
650            once: true,
651        });
652        self
653    }
654
655    /// The store failure a root scan hit during the run, if any. Every other
656    /// read fails through the engine's channel (`get` / `call_method` return
657    /// `Err`); `root` has none, so it serves an empty scan and leaves the
658    /// failure here for the runner to report.
659    pub fn take_root_failure(&self) -> Option<OqxError> {
660        self.root_failure.borrow_mut().take()
661    }
662
663    // ---- SQL helpers ------------------------------------------------------------------
664
665    fn all(&self, sql: &str, params: &[SqlValue]) -> oqx::Result<Vec<Object>> {
666        self.statements_run.set(self.statements_run.get() + 1);
667        fetch_rows(self.conn, sql, params).map_err(sql_err)
668    }
669
670    fn one(&self, sql: &str, params: &[SqlValue]) -> oqx::Result<Option<Object>> {
671        Ok(self.all(sql, params)?.into_iter().next())
672    }
673
674    fn scalar(&self, sql: &str, params: &[SqlValue]) -> oqx::Result<Value> {
675        Ok(self
676            .one(sql, params)?
677            .and_then(|o| o.values().next().cloned())
678            .unwrap_or(Value::Undefined))
679    }
680
681    fn exists(&self, sql: &str, params: &[SqlValue]) -> oqx::Result<bool> {
682        self.statements_run.set(self.statements_run.get() + 1);
683        let mut stmt = self.conn.prepare_cached(sql).map_err(sql_err)?;
684        stmt.exists(params_from_iter(params.iter()))
685            .map_err(sql_err)
686    }
687
688    fn tag_all(rows: Vec<Object>, t: Target) -> Value {
689        Value::Array(tag_rows(rows, t))
690    }
691
692    fn tag(row: Object, t: Target) -> Value {
693        tag_row(row, t)
694    }
695
696    /// The root row (`spec/surface` §1.1, 2.0; `spec/oqx` 0.18 `root_object`):
697    /// the repository, reached as `^$it` from a top-level row (`0^$it` from any
698    /// depth). Its own keys are the five collections as lazy markers (in
699    /// [`ALL_TARGETS`] order), so
700    /// `entries(^$it)` names them without running a scan and `^$it.docs` is
701    /// the same scan as `^docs`; `get` answers `id` with the repository id (an
702    /// intrinsic, not an entry). Same shape as the reference's root row.
703    fn root_row(&self) -> Value {
704        let mut o = Object::with_capacity(ALL_TARGETS.len());
705        for t in ALL_TARGETS {
706            o.insert(t.as_str(), scan_marker(t));
707        }
708        Value::Object(o)
709    }
710
711    // ---- roots (ordered for a stable (path, id) default) ------------------------------
712
713    /// The joined roots drive from `docs` in `(repo_id, path)` index order
714    /// (`CROSS JOIN` fixes the loop order) and reach the rows of each doc
715    /// through their `doc_id` index, so the `ORDER BY d.path, <id>` sorts one
716    /// document's rows at a time instead of every full row of the repo in a
717    /// temp b-tree. The `+` on the inner `repo_id` term keeps it a filter
718    /// (SQLite's unary-plus idiom: the term is not used for index selection,
719    /// which — without `ANALYZE` stats — would otherwise pick the
720    /// `(repo_id, type)` index and rescan the repo per document). Same rows,
721    /// same order: the key `(path, id)` is total (`UNIQUE (repo_id, path)`;
722    /// the id is a primary key), so no plan can order them differently.
723    fn root_scan(&self, t: Target) -> oqx::Result<Value> {
724        let repo = [SqlValue::Text(self.repo_id.clone())];
725        let sql = match t {
726            Target::Docs => {
727                "SELECT * FROM docs WHERE repo_id = ?1 AND deleted_commit IS NULL ORDER BY path, doc_id"
728            }
729            Target::Blocks => {
730                "SELECT b.*, d.path AS __path FROM docs d CROSS JOIN blocks b ON b.doc_id = d.doc_id
731                 WHERE d.repo_id = ?1 AND +b.repo_id = ?1 AND b.deleted_commit IS NULL AND d.deleted_commit IS NULL
732                 ORDER BY d.path, b.block_id"
733            }
734            Target::Nodes => {
735                "SELECT n.*, d.path AS __path FROM docs d CROSS JOIN nodes n ON n.doc_id = d.doc_id
736                 WHERE d.repo_id = ?1 AND +n.repo_id = ?1 AND d.deleted_commit IS NULL ORDER BY d.path, n.node_id"
737            }
738            Target::Links => {
739                "SELECT e.*, d.path AS __path FROM docs d CROSS JOIN edges e ON e.src_doc = d.doc_id
740                 WHERE d.repo_id = ?1 AND +e.repo_id = ?1 AND e.to_commit IS NULL AND d.deleted_commit IS NULL
741                 ORDER BY d.path, e.edge_id"
742            }
743            // The history (4.7): its own statement, in the same `(path, id)`
744            // keyset order as every target — `(path as of the revision, rev_id)`.
745            Target::Revisions => {
746                let sql = format!(
747                    "SELECT {REVISION_COLS} FROM {REVISION_FROM} WHERE d.repo_id = ?1 ORDER BY r.path, r.rev_id"
748                );
749                return Ok(Self::tag_all(self.all(&sql, &repo)?, t));
750            }
751        };
752        Ok(Self::tag_all(self.all(sql, &repo)?, t))
753    }
754
755    /// A document's revisions (the `revisions` relation of a docs row, §1.2,
756    /// 4.7): oldest first, as `docs_history` lists them.
757    fn doc_revisions(&self, doc_id: &str) -> oqx::Result<Value> {
758        let sql = format!(
759            "SELECT {REVISION_COLS} FROM {REVISION_FROM} WHERE r.doc_id = ?1 ORDER BY r.seq"
760        );
761        Ok(Self::tag_all(
762            self.all(&sql, &[SqlValue::Text(doc_id.to_owned())])?,
763            Target::Revisions,
764        ))
765    }
766
767    // ---- properties ---------------------------------------------------------------------
768
769    /// A property row decoded to a plain scalar; a range-shaped string stays a
770    /// string (`range(prop)` is the opt-in).
771    fn decode_prop(r: &Object) -> Value {
772        let get = |k: &str| r.get(k).cloned().unwrap_or(Value::Undefined);
773        match get("type").as_str().unwrap_or("") {
774            "number" => get("val_num"),
775            "bool" => Value::Bool(get("val_bool").truthy()),
776            "null" => Value::Null,
777            "json" => parse_json(&get("val_json")),
778            _ => get("val_text"),
779        }
780    }
781
782    /// The scalar-vs-list rule: exactly one `card = scalar` row → the scalar;
783    /// otherwise the array; no row → the nested object under `key.`.
784    fn doc_prop(&self, doc_id: &str, key: &str, source: Option<&str>) -> oqx::Result<Value> {
785        let rows = match source {
786            Some(s) => self.all(
787                "SELECT * FROM properties WHERE doc_id = ?1 AND key = ?2 AND source = ?3 AND deleted_commit IS NULL ORDER BY ord",
788                &[SqlValue::Text(doc_id.to_owned()), SqlValue::Text(key.to_owned()), SqlValue::Text(s.to_owned())],
789            )?,
790            None => self.all(
791                "SELECT * FROM properties WHERE doc_id = ?1 AND key = ?2 AND deleted_commit IS NULL ORDER BY ord",
792                &[SqlValue::Text(doc_id.to_owned()), SqlValue::Text(key.to_owned())],
793            )?,
794        };
795        if rows.is_empty() {
796            return self.doc_prop_object(doc_id, key, source);
797        }
798        if rows.len() == 1 && rows[0].get("card").and_then(Value::as_str) == Some("scalar") {
799            return Ok(Self::decode_prop(&rows[0]));
800        }
801        Ok(Value::Array(rows.iter().map(Self::decode_prop).collect()))
802    }
803
804    /// The nested object rebuilt from flattened dotted keys under `prefix.`
805    /// (`Undefined` when none); leaves decoded.
806    fn doc_prop_object(
807        &self,
808        doc_id: &str,
809        prefix: &str,
810        source: Option<&str>,
811    ) -> oqx::Result<Value> {
812        let like = SqlValue::Text(format!("{prefix}.%"));
813        let rows = match source {
814            Some(s) => self.all(
815                "SELECT * FROM properties WHERE doc_id = ?1 AND key LIKE ?2 AND source = ?3 AND deleted_commit IS NULL ORDER BY ord",
816                &[SqlValue::Text(doc_id.to_owned()), like, SqlValue::Text(s.to_owned())],
817            )?,
818            None => self.all(
819                "SELECT * FROM properties WHERE doc_id = ?1 AND key LIKE ?2 AND deleted_commit IS NULL ORDER BY ord",
820                &[SqlValue::Text(doc_id.to_owned()), like],
821            )?,
822        };
823        if rows.is_empty() {
824            return Ok(Value::Undefined);
825        }
826        let mut out = Object::new();
827        for r in &rows {
828            let key = r.get("key").and_then(Value::as_str).unwrap_or("");
829            let rest: Vec<&str> = key[(prefix.len() + 1).min(key.len())..]
830                .split('.')
831                .collect();
832            set_nested(&mut out, &rest, Self::decode_prop(r));
833        }
834        Ok(Value::Object(out))
835    }
836
837    /// The `data` / `frontmatter` / `inline` bag as a plain object: one entry
838    /// per top-level key in key order, each valued by [`Self::doc_prop`].
839    /// `data` (`None`) is frontmatter ∪ inline — the keys deduped, each valued
840    /// by the merged read.
841    fn doc_prop_bag(&self, doc_id: &str, source: Option<&str>) -> oqx::Result<Value> {
842        let keys = match source {
843            Some(s) => self.all(
844                "SELECT DISTINCT key FROM properties WHERE doc_id = ?1 AND source = ?2 AND deleted_commit IS NULL ORDER BY key",
845                &[SqlValue::Text(doc_id.to_owned()), SqlValue::Text(s.to_owned())],
846            )?,
847            None => self.all(
848                "SELECT DISTINCT key FROM properties WHERE doc_id = ?1 AND source IN ('frontmatter', 'inline') AND deleted_commit IS NULL ORDER BY key",
849                &[SqlValue::Text(doc_id.to_owned())],
850            )?,
851        };
852        let mut out = Object::new();
853        for k in keys {
854            let key = k.get("key").and_then(Value::as_str).unwrap_or("");
855            let top = key.split('.').next().unwrap_or("");
856            if !out.contains_key(top) {
857                let v = self.doc_prop(doc_id, top, source)?;
858                out.insert(top, v);
859            }
860        }
861        Ok(Value::Object(out))
862    }
863
864    /// `tags` on a document: authored ∪ hashtags, each list as the property
865    /// rule reads it (a scalar-authored `tags: x` is one element), deduped by
866    /// canonical JSON of each element, authored first in authored order, then
867    /// the computed `$tags` row (body hashtags, `spec/properties` §3.3) in
868    /// document order; `Null` when both are absent.
869    fn doc_tags(&self, doc_id: &str) -> oqx::Result<Value> {
870        fn as_list(v: Value) -> Vec<Value> {
871            match v {
872                Value::Undefined | Value::Null => Vec::new(),
873                Value::Array(a) => a,
874                other => vec![other],
875            }
876        }
877        let authored = as_list(self.doc_prop(doc_id, "tags", None)?);
878        let hashtags = as_list(self.doc_prop(doc_id, "$tags", Some("computed"))?);
879        if authored.is_empty() && hashtags.is_empty() {
880            return Ok(Value::Null);
881        }
882        let mut seen: Vec<String> = Vec::new();
883        let mut out = Vec::new();
884        for v in authored.into_iter().chain(hashtags) {
885            let k = v.to_canonical_json().to_string();
886            if seen.contains(&k) {
887                continue;
888            }
889            seen.push(k);
890            out.push(v);
891        }
892        Ok(Value::Array(out))
893    }
894
895    // ---- structure ----------------------------------------------------------------------
896
897    /// The ordinal of a block's top-level ancestor (section ranges are in
898    /// top-level ordinals).
899    fn top_ordinal(&self, block: &Value) -> oqx::Result<Value> {
900        let ordinal = col(block, "ordinal").clone();
901        if col(block, "parent_block").is_absent() {
902            return Ok(ordinal);
903        }
904        let ap = col_str(block, "ancestor_path");
905        let Some(first) = ap.split('/').find(|s| !s.is_empty()) else {
906            return Ok(ordinal);
907        };
908        let r = self.scalar(
909            "SELECT ordinal FROM blocks WHERE doc_id = ?1 AND block_id = ?2",
910            &[
911                SqlValue::Text(col_str(block, "doc_id")),
912                SqlValue::Text(first.to_owned()),
913            ],
914        )?;
915        Ok(if r.is_absent() { ordinal } else { r })
916    }
917
918    /// A document's live blocks in document order — pre-order over the
919    /// containment tree (children by `ordinal` under their parent; a row whose
920    /// parent is not live is a root) — tagged, with `__path` = `path`.
921    fn doc_blocks_preorder(&self, doc_id: &str, path: &str) -> oqx::Result<Vec<Value>> {
922        let rows = self.all(
923            "SELECT b.*, ?1 AS __path FROM blocks b WHERE b.doc_id = ?2 AND b.deleted_commit IS NULL ORDER BY b.ordinal, b.block_id",
924            &[SqlValue::Text(path.to_owned()), SqlValue::Text(doc_id.to_owned())],
925        )?;
926        let ids: Vec<String> = rows
927            .iter()
928            .map(|r| {
929                r.get("block_id")
930                    .and_then(Value::as_str)
931                    .unwrap_or("")
932                    .to_owned()
933            })
934            .collect();
935        let parent_index: Vec<Option<usize>> = rows
936            .iter()
937            .map(|r| {
938                r.get("parent_block")
939                    .and_then(Value::as_str)
940                    .and_then(|p| ids.iter().position(|id| id == p))
941            })
942            .collect();
943        let mut children: Vec<Vec<usize>> = vec![Vec::new(); rows.len()];
944        let mut roots = Vec::new();
945        for (i, p) in parent_index.iter().enumerate() {
946            match p {
947                Some(p) => children[*p].push(i),
948                None => roots.push(i),
949            }
950        }
951        fn walk(i: usize, children: &[Vec<usize>], order: &mut Vec<usize>) {
952            order.push(i);
953            for &c in &children[i] {
954                walk(c, children, order);
955            }
956        }
957        let mut order = Vec::with_capacity(rows.len());
958        for r in roots {
959            walk(r, &children, &mut order);
960        }
961        let mut slots: Vec<Option<Object>> = rows.into_iter().map(Some).collect();
962        Ok(order
963            .into_iter()
964            .map(|i| Self::tag(slots[i].take().expect("visited once"), Target::Blocks))
965            .collect())
966    }
967
968    fn jattr(row: &Value, k: &str) -> Value {
969        match parse_json(col(row, "attrs")) {
970            Value::Object(o) => o.get(k).cloned().unwrap_or(Value::Undefined),
971            _ => Value::Undefined,
972        }
973    }
974
975    /// `Ok(None)` when `key` is not a relation of `t`.
976    fn relation(&self, row: &Value, t: Target, key: &str) -> oqx::Result<Option<Value>> {
977        let path = || SqlValue::Text(col_str(row, "__path"));
978        let doc_id = || SqlValue::Text(col_str(row, "doc_id"));
979        let doc_path = || SqlValue::Text(col_str(row, "path"));
980        let block_id = || SqlValue::Text(col_str(row, "block_id"));
981        Ok(Some(match (t, key) {
982            (Target::Docs, "nodes") => {
983                // Document order: block-less nodes first, then by the owning
984                // block's pre-order rank, `span_start`, `node_id`.
985                let rows = self.all(
986                    "SELECT n.*, ?1 AS __path FROM nodes n WHERE n.doc_id = ?2 ORDER BY n.node_id",
987                    &[doc_path(), doc_id()],
988                )?;
989                let blocks = self.doc_blocks_preorder(&col_str(row, "doc_id"), &col_str(row, "path"))?;
990                let rank: HashMap<String, usize> = blocks
991                    .iter()
992                    .enumerate()
993                    .map(|(i, b)| (col_str(b, "block_id"), i))
994                    .collect();
995                let mut keyed: Vec<((usize, usize, f64, String), Object)> = rows
996                    .into_iter()
997                    .map(|r| {
998                        let block = r.get("block_id").and_then(Value::as_str);
999                        let (has_block, rk) = match block {
1000                            None => (0, 0),
1001                            Some(b) => (1, rank.get(b).copied().unwrap_or(usize::MAX)),
1002                        };
1003                        let span = r.get("span_start").and_then(Value::as_f64).unwrap_or(-1.0);
1004                        let id = r.get("node_id").and_then(Value::as_str).unwrap_or("").to_owned();
1005                        ((has_block, rk, span, id), r)
1006                    })
1007                    .collect();
1008                keyed.sort_by(|a, b| {
1009                    a.0.0
1010                        .cmp(&b.0.0)
1011                        .then(a.0.1.cmp(&b.0.1))
1012                        .then(a.0.2.total_cmp(&b.0.2))
1013                        .then(a.0.3.cmp(&b.0.3))
1014                });
1015                Value::Array(keyed.into_iter().map(|(_, r)| Self::tag(r, Target::Nodes)).collect())
1016            }
1017            (Target::Docs, "blocks") => {
1018                Value::Array(self.doc_blocks_preorder(&col_str(row, "doc_id"), &col_str(row, "path"))?)
1019            }
1020            // A document's revision list (`spec/surface` §1.2, 4.7), oldest first.
1021            (Target::Docs, "revisions") => self.doc_revisions(&col_str(row, "doc_id"))?,
1022            // The linked / linking DOCUMENTS are reached through the link rows
1023            // (3.0 follow-up, §9: the `out` / `in` relations are gone):
1024            // `out_links collect distinct { from dst }` and `in_links collect
1025            // distinct { from doc }`.
1026            (Target::Docs, "out_links") => Self::tag_all(
1027                self.all(
1028                    "SELECT e.*, ?1 AS __path FROM edges e WHERE e.src_doc = ?2 AND e.to_commit IS NULL ORDER BY e.predicate, e.edge_id",
1029                    &[doc_path(), doc_id()],
1030                )?,
1031                Target::Links,
1032            ),
1033            (Target::Docs, "in_links") => Self::tag_all(
1034                self.all(
1035                    "SELECT e.*, d.path AS __path FROM edges e JOIN docs d ON d.doc_id = e.src_doc
1036                     WHERE e.dst_node = ?1 AND e.to_commit IS NULL AND d.deleted_commit IS NULL ORDER BY e.predicate, e.edge_id",
1037                    &[doc_id()],
1038                )?,
1039                Target::Links,
1040            ),
1041            (Target::Blocks, "children") => Self::tag_all(
1042                self.all(
1043                    "SELECT b.*, ?1 AS __path FROM blocks b WHERE b.parent_block = ?2 AND b.deleted_commit IS NULL ORDER BY b.ordinal, b.block_id",
1044                    &[path(), block_id()],
1045                )?,
1046                Target::Blocks,
1047            ),
1048            (Target::Blocks, "nodes") => Self::tag_all(
1049                self.all(
1050                    "SELECT n.*, ?1 AS __path FROM nodes n WHERE n.block_id = ?2 ORDER BY n.span_start, n.node_id",
1051                    &[path(), block_id()],
1052                )?,
1053                Target::Nodes,
1054            ),
1055            (Target::Blocks, "out_links") => Self::tag_all(
1056                self.all(
1057                    "SELECT e.*, ?1 AS __path FROM edges e WHERE e.src_block = ?2 AND e.to_commit IS NULL ORDER BY e.predicate, e.edge_id",
1058                    &[path(), block_id()],
1059                )?,
1060                Target::Links,
1061            ),
1062            (Target::Blocks, "section") => {
1063                let top = to_sql(&self.top_ordinal(row)?);
1064                Self::tag_all(
1065                    self.all(
1066                        "SELECT n.*, ?1 AS __path FROM nodes n WHERE n.doc_id = ?2 AND n.kind = 'md:section'
1067                           AND json_extract(n.attrs,'$.first_ordinal') <= ?3 AND json_extract(n.attrs,'$.last_ordinal') >= ?4
1068                         ORDER BY json_extract(n.attrs,'$.first_ordinal'), n.node_id",
1069                        &[path(), doc_id(), top.clone(), top],
1070                    )?,
1071                    Target::Nodes,
1072                )
1073            }
1074            (Target::Nodes, "blocks") => {
1075                let (f, l) = (Self::jattr(row, "first_ordinal"), Self::jattr(row, "last_ordinal"));
1076                if f.is_absent() || l.is_absent() {
1077                    return Ok(Some(Value::Array(Vec::new())));
1078                }
1079                let (f, l) = (
1080                    f.as_f64().unwrap_or(f64::NAN),
1081                    l.as_f64().unwrap_or(f64::NAN),
1082                );
1083                let rows = self.doc_blocks_preorder(&col_str(row, "doc_id"), &col_str(row, "__path"))?;
1084                let mut kept: Vec<Value> = Vec::new();
1085                for b in rows {
1086                    let t = self.top_ordinal(&b)?.as_f64().unwrap_or(f64::NAN);
1087                    if t >= f && t <= l {
1088                        kept.push(b);
1089                    }
1090                }
1091                Value::Array(kept)
1092            }
1093            (Target::Nodes, "subsections") => {
1094                let (f, l, lvl) = (
1095                    Self::jattr(row, "first_ordinal"),
1096                    Self::jattr(row, "last_ordinal"),
1097                    Self::jattr(row, "level"),
1098                );
1099                if f.is_absent() {
1100                    return Ok(Some(Value::Array(Vec::new())));
1101                }
1102                Self::tag_all(
1103                    self.all(
1104                        "SELECT n.*, ?1 AS __path FROM nodes n WHERE n.doc_id = ?2 AND n.kind = 'md:section'
1105                           AND json_extract(n.attrs,'$.first_ordinal') >= ?3 AND json_extract(n.attrs,'$.last_ordinal') <= ?4
1106                           AND json_extract(n.attrs,'$.level') > ?5 ORDER BY json_extract(n.attrs,'$.first_ordinal'), n.node_id",
1107                        &[path(), doc_id(), to_sql(&f), to_sql(&l), to_sql(&lvl)],
1108                    )?,
1109                    Target::Nodes,
1110                )
1111            }
1112            (Target::Nodes, "children") => {
1113                let (f, l, lvl) = (
1114                    Self::jattr(row, "first_ordinal"),
1115                    Self::jattr(row, "last_ordinal"),
1116                    Self::jattr(row, "level"),
1117                );
1118                if f.is_absent() {
1119                    return Ok(Some(Value::Array(Vec::new())));
1120                }
1121                Self::tag_all(
1122                    self.all(
1123                        "SELECT i.*, ?1 AS __path FROM nodes i WHERE i.doc_id = ?2 AND i.kind = 'md:section'
1124                           AND json_extract(i.attrs,'$.level') > ?3
1125                           AND json_extract(i.attrs,'$.first_ordinal') >= ?4 AND json_extract(i.attrs,'$.last_ordinal') <= ?5
1126                           AND NOT EXISTS (SELECT 1 FROM nodes m WHERE m.doc_id = i.doc_id AND m.kind = 'md:section'
1127                             AND json_extract(m.attrs,'$.level') > ?6 AND json_extract(m.attrs,'$.level') < json_extract(i.attrs,'$.level')
1128                             AND json_extract(m.attrs,'$.first_ordinal') <= json_extract(i.attrs,'$.first_ordinal')
1129                             AND json_extract(m.attrs,'$.last_ordinal') >= json_extract(i.attrs,'$.last_ordinal'))
1130                         ORDER BY json_extract(i.attrs,'$.first_ordinal'), i.node_id",
1131                        &[path(), doc_id(), to_sql(&lvl), to_sql(&f), to_sql(&l), to_sql(&lvl)],
1132                    )?,
1133                    Target::Nodes,
1134                )
1135            }
1136            _ => return Ok(None),
1137        }))
1138    }
1139
1140    // ---- owning-entity reach-through: foreign-key elimination ------------------------
1141    //
1142    // The owner is handed out as a LAZY row (`LAZY_KEY`) whose identity columns
1143    // are already known from the child — a block's/node's `doc_id` and `__path`
1144    // name its document, an edge's `src_doc` and `__path` its source doc, a
1145    // node's `block_id` (+ `doc_id`, `__path`) its block — so `doc.id` and
1146    // `doc.path` (and `block.id`/`block.path`/`block.doc_id` on a node)
1147    // read those columns and run NO statement, exactly like the bare `doc_id`;
1148    // the full owner row is loaded on the first read of anything else
1149    // (`doc.format`, `block.text`). The translator mirrors this in SQL
1150    // (`doc.id` → the FK column). Port of the reference's `lazyOwner` Proxy.
1151
1152    fn lazy_owner(known: &[(&str, Value)], t: Target) -> Value {
1153        let mut o = Object::with_capacity(known.len() + 2);
1154        for (k, v) in known {
1155            o.insert(*k, v.clone());
1156        }
1157        o.insert(LAZY_KEY, Value::Bool(true));
1158        tag_row(o, t)
1159    }
1160
1161    fn owning_doc(&self, row: &Value) -> oqx::Result<Value> {
1162        let id = match col(row, "doc_id") {
1163            Value::Undefined | Value::Null => col(row, "src_doc").clone(),
1164            v => v.clone(),
1165        };
1166        if id.is_absent() {
1167            return Ok(absent_single());
1168        }
1169        match col(row, "__path") {
1170            Value::Str(path) => Ok(Self::lazy_owner(
1171                &[("doc_id", id), ("path", Value::Str(path.clone()))],
1172                Target::Docs,
1173            )),
1174            _ => Ok(self
1175                .load_owner(Target::Docs, &js_string(&id))?
1176                .unwrap_or_else(absent_single)),
1177        }
1178    }
1179
1180    /// `dst` on a link row (`spec/surface` §1.2, 3.0 follow-up): the
1181    /// destination DOCUMENT row when the link points at one (`dst_kind ==
1182    /// "document"` and the document exists — a phantom target has the kind
1183    /// and no row), read by `dst_id` exactly as `dst_path` is; absent for a
1184    /// `block` or `external` destination (never reached into). `doc` stays
1185    /// the source document.
1186    fn destination_doc(&self, row: &Value) -> oqx::Result<Value> {
1187        if col(row, "dst_kind") != &Value::Str("document".to_owned()) {
1188            return Ok(absent_single());
1189        }
1190        Ok(self
1191            .load_owner(Target::Docs, &col_str(row, "dst_node"))?
1192            .unwrap_or_else(absent_single))
1193    }
1194
1195    /// `doc` on a revision row (`spec/surface` §1.2, 4.7): the document's
1196    /// CURRENT live row — the revision's `path` may be an earlier one — and
1197    /// absent (the single-with-no-row marker, as `dst` on a dangling link)
1198    /// for a tombstoned document: its revisions are rows, `doc == null` tells
1199    /// them apart. Read in full, as the reference does (not a lazy owner: the
1200    /// liveness test is the point of the read).
1201    fn revision_doc(&self, row: &Value) -> oqx::Result<Value> {
1202        Ok(self
1203            .one(
1204                "SELECT * FROM docs WHERE doc_id = ?1 AND deleted_commit IS NULL",
1205                &[SqlValue::Text(col_str(row, "doc_id"))],
1206            )?
1207            .map_or_else(absent_single, |o| Self::tag(o, Target::Docs)))
1208    }
1209
1210    fn owning_block(&self, row: &Value) -> oqx::Result<Value> {
1211        let id = col(row, "block_id");
1212        if !id.truthy() {
1213            return Ok(absent_single());
1214        }
1215        match col(row, "__path") {
1216            Value::Str(path) => Ok(Self::lazy_owner(
1217                &[
1218                    ("block_id", id.clone()),
1219                    ("doc_id", col(row, "doc_id").clone()),
1220                    ("__path", Value::Str(path.clone())),
1221                ],
1222                Target::Blocks,
1223            )),
1224            _ => Ok(self
1225                .load_owner(Target::Blocks, &js_string(id))?
1226                .unwrap_or_else(absent_single)),
1227        }
1228    }
1229
1230    /// The full owner row by id (`None` when it is not in the store), read
1231    /// at most once per run.
1232    fn load_owner(&self, t: Target, id: &str) -> oqx::Result<Option<Value>> {
1233        let key = (t, id.to_owned());
1234        if let Some(v) = self.owners.borrow().get(&key) {
1235            return Ok(v.clone());
1236        }
1237        let loaded = match t {
1238            Target::Docs => self
1239                .one(
1240                    "SELECT * FROM docs WHERE doc_id = ?1",
1241                    &[SqlValue::Text(id.to_owned())],
1242                )?
1243                .map(|o| Self::tag(o, Target::Docs)),
1244            _ => self
1245                .one(
1246                    "SELECT b.*, d.path AS __path FROM blocks b JOIN docs d ON d.doc_id = b.doc_id WHERE b.block_id = ?1",
1247                    &[SqlValue::Text(id.to_owned())],
1248                )?
1249                .map(|o| Self::tag(o, Target::Blocks)),
1250        };
1251        self.owners.borrow_mut().insert(key, loaded.clone());
1252        Ok(loaded)
1253    }
1254
1255    /// Whether reading `key` off a lazy owner of `t` needs the full row. The
1256    /// known columns answer the identity (`id`, `path`), the self alias, the
1257    /// relations (keyed by `doc_id` / `path` / `block_id`), the properties
1258    /// and source handles (keyed by `doc_id`), `raw`, `title` and `tags` on
1259    /// docs (by id), `updated_at` on blocks (by id), a bare target name (an
1260    /// error) and an unknown `$x` (absent); everything that reads another
1261    /// column — `format`, `hash`, `updated_at` on docs; `type`, `text`,
1262    /// `attrs`, `ordinal`, `depth`, an attrs key, `section`, `raw`/`hash` on
1263    /// blocks — loads it.
1264    fn lazy_needs_load(t: Target, key: &str) -> bool {
1265        match t {
1266            Target::Docs => matches!(key, "format" | "hash" | "updated_at"),
1267            Target::Blocks => {
1268                !matches!(
1269                    key,
1270                    "id" | "path"
1271                        | "updated_at"
1272                        | "$self"
1273                        | "doc_id"
1274                        | "block"
1275                        | "doc"
1276                        | "children"
1277                        | "nodes"
1278                        | "out_links"
1279                ) && Target::parse(key).is_none()
1280            }
1281            // never handed out as lazy owners
1282            Target::Nodes | Target::Links | Target::Revisions => true,
1283        }
1284    }
1285
1286    /// A lazy owner with the full row in its place when `key` needs it; the
1287    /// marker itself otherwise (`None` for a row that is not a lazy owner, or
1288    /// whose owner is gone from the store — then the partial columns stand).
1289    fn resolve_lazy(&self, row: &Value, t: Target, key: &str) -> oqx::Result<Option<Value>> {
1290        if !is_lazy_owner(row) || !Self::lazy_needs_load(t, key) {
1291            return Ok(None);
1292        }
1293        let id_col = if t == Target::Docs {
1294            "doc_id"
1295        } else {
1296            "block_id"
1297        };
1298        self.load_owner(t, &col_str(row, id_col))
1299    }
1300
1301    // ---- engine attributes --------------------------------------------------------------
1302
1303    fn null_if_absent(v: Value) -> Value {
1304        if v.is_absent() { Value::Null } else { v }
1305    }
1306
1307    /// The engine attributes (see the name rule above; `spec/surface` §1.2,
1308    /// 3.0): bare, snake_case, winning on collision. `path` (and the edge
1309    /// field `dst_path`) is the REFERENCE form (`/a/b.md`, §1 "Paths", 2.0):
1310    /// the rows carry the storage form (`path`, the `__path` join column) and
1311    /// the read roots it, so nothing below the binding changes. The runner
1312    /// roots the string literals a query compares them with. The caller has
1313    /// checked `name` against [`attributes`], so the fallthrough is unreachable
1314    /// in practice (`Undefined`).
1315    fn attribute(&self, row: &Value, t: Target, name: &str) -> oqx::Result<Value> {
1316        let c = |k: &str| col(row, k).clone();
1317        let rooted = |k: &str| Value::Str(reference_path(&col_str(row, k)));
1318        Ok(match (t, name) {
1319            (Target::Docs, "id") => c("doc_id"),
1320            (Target::Docs, "path") => rooted("path"),
1321            (Target::Docs, "hash") => Self::null_if_absent(c("file_hash")),
1322            (Target::Docs, "updated_at") => Self::null_if_absent(self.scalar(
1323                "SELECT c.ts FROM revisions r JOIN commits c ON c.commit_id = r.commit_id WHERE r.rev_id = ?1",
1324                &[to_sql(&c("current_rev"))],
1325            )?),
1326            // `raw`: the exact file bytes (`spec/store` §6.1, frontmatter included).
1327            (Target::Docs, "raw") => {
1328                match omgbase_store::read::reconstruct(self.conn, &col_str(row, "doc_id")) {
1329                    Ok(Some(s)) => Value::Str(s),
1330                    Ok(None) => Value::Null,
1331                    Err(e) => return Err(OqxError::eval(e.to_string())),
1332                }
1333            }
1334            // `title`: the computed title (`spec/properties` §3.3 — the
1335            // authored title, else the first H1, else absent → null); the
1336            // store writes it under `$title`. `data.title` is the authored
1337            // one alone.
1338            (Target::Docs, "title") => {
1339                Self::null_if_absent(self.doc_prop(&col_str(row, "doc_id"), "$title", Some("computed"))?)
1340            }
1341            // `tags`: authored tags ∪ body `#hashtags` (the computed `$tags`
1342            // row); `data.tags` is the authored list alone.
1343            (Target::Docs, "tags") => self.doc_tags(&col_str(row, "doc_id"))?,
1344            (Target::Docs, "format") => c("format"),
1345            (Target::Blocks, "id") => c("block_id"),
1346            (Target::Blocks, "path") => rooted("__path"),
1347            // `raw`: the block's raw source bytes — the blob its `raw_hash`
1348            // names (a container's raw holds its children verbatim); `text`
1349            // is the normalized text.
1350            (Target::Blocks, "raw") => match c("raw_hash") {
1351                Value::Str(hex) => {
1352                    let hash = omgbase_store::tree::from_hex(&hex)
1353                        .map_err(|e| OqxError::eval(e.to_string()))?;
1354                    let bytes: Option<Vec<u8>> = self
1355                        .conn
1356                        .query_row(
1357                            "SELECT bytes FROM blobs WHERE hash = ?1",
1358                            rusqlite::params![hash],
1359                            |r| r.get(0),
1360                        )
1361                        .optional()
1362                        .map_err(sql_err)?;
1363                    self.statements_run.set(self.statements_run.get() + 1);
1364                    bytes.map_or(Value::Null, |b| {
1365                        Value::Str(String::from_utf8_lossy(&b).into_owned())
1366                    })
1367                }
1368                _ => Value::Null,
1369            },
1370            (Target::Blocks, "hash") => Self::null_if_absent(c("raw_hash")),
1371            (Target::Blocks, "updated_at") => Self::null_if_absent(self.scalar(
1372                "SELECT MAX(c.ts) FROM block_changes bc JOIN commits c ON c.commit_id = bc.commit_id WHERE bc.block_id = ?1",
1373                &[to_sql(&c("block_id"))],
1374            )?),
1375            // The structural columns and the foreign keys under the surface's
1376            // names (§1.2, 3.0).
1377            (Target::Blocks, "doc_id" | "type" | "text" | "ordinal" | "depth") => c(name),
1378            (Target::Blocks | Target::Nodes, "attrs") => parse_json(&c("attrs")),
1379            (Target::Nodes, "id") => c("node_id"),
1380            (Target::Nodes, "path") => rooted("__path"),
1381            (Target::Nodes, "doc_id" | "kind" | "name" | "value") => c(name),
1382            (Target::Nodes, "block_id") => Self::null_if_absent(c("block_id")),
1383            // edges: the store's columns under the surface's names (a foreign
1384            // key is named for what it is, the `src_field` column is `field`).
1385            (Target::Links, "id") => c("edge_id"),
1386            (Target::Links, "path") => rooted("__path"),
1387            (Target::Links, "doc_id") => c("src_doc"),
1388            (Target::Links, "block_id") => Self::null_if_absent(c("src_block")),
1389            (Target::Links, "via_id") => Self::null_if_absent(c("via_node")),
1390            (Target::Links, "dst_id") => c("dst_node"),
1391            (Target::Links, "dst_path") => match self.scalar(
1392                "SELECT path FROM docs WHERE doc_id = ?1",
1393                &[to_sql(&c("dst_node"))],
1394            )? {
1395                Value::Undefined | Value::Null => Value::Null,
1396                p => Value::Str(reference_path(&js_string(&p))),
1397            },
1398            (Target::Links, "uri") => Self::null_if_absent(self.scalar(
1399                "SELECT uri FROM external_nodes WHERE node_id = ?1",
1400                &[to_sql(&c("dst_node"))],
1401            )?),
1402            (Target::Links, "field") => Self::null_if_absent(c("src_field")),
1403            (Target::Links, "predicate" | "provenance" | "dst_kind" | "anchor") => c(name),
1404            // revisions: the `revisions` × `commits` columns under
1405            // docs_history's names (`spec/surface` §1.2, 4.7). `rendered_hash`
1406            // is a blob, already hex (`sql_value`).
1407            (Target::Revisions, "id" | "rev") => c("rev_id"),
1408            (Target::Revisions, "path") => rooted("path"),
1409            (Target::Revisions, "seq" | "doc_id" | "ts" | "origin") => c(name),
1410            (Target::Revisions, "commit") => c("commit_id"),
1411            (Target::Revisions, "actor" | "reason") => Self::null_if_absent(c(name)),
1412            (Target::Revisions, "hash") => c("rendered_hash"),
1413            (Target::Revisions, "is_current") => Value::Bool(matches!(
1414                c("is_current"),
1415                Value::Number(n) if n == 1.0
1416            )),
1417            _ => Value::Undefined,
1418        })
1419    }
1420
1421    // ---- row functions (methods on `$self`) ----------------------------------------------
1422
1423    fn filter_invalid(msg: String) -> Option<oqx::Result<Value>> {
1424        Some(Err(OqxError::eval(msg)))
1425    }
1426
1427    fn require_target(t: Target, want: Target, name: &str) -> Option<oqx::Result<Value>> {
1428        (t != want).then(|| {
1429            Err(OqxError::eval(format!(
1430                "{name}() is only available on the {} target",
1431                want.as_str()
1432            )))
1433        })
1434    }
1435
1436    fn sql_result(r: oqx::Result<bool>) -> oqx::Result<Value> {
1437        r.map(Value::Bool)
1438    }
1439
1440    fn row_method(
1441        &self,
1442        name: &str,
1443        row: &Value,
1444        t: Target,
1445        args: &[Value],
1446    ) -> Option<oqx::Result<Value>> {
1447        let c = |k: &str| col(row, k).clone();
1448        match name {
1449            "text" => Some(self.text_match(t, row, &arg_or_empty(args, 0))),
1450            "semantic" => Some(self.semantic_score(t, row, &arg_or_empty(args, 0))),
1451            "has_anchor" => Self::require_target(t, Target::Blocks, name).or_else(|| {
1452                Some(Self::sql_result(self.exists(
1453                    "SELECT 1 FROM edges WHERE src_block = ?1 AND anchor IS NOT NULL LIMIT 1",
1454                    &[to_sql(&c("block_id"))],
1455                )))
1456            }),
1457            "child_count" => Self::require_target(t, Target::Blocks, name).or_else(|| {
1458                Some(self.scalar(
1459                    "SELECT COUNT(*) FROM blocks WHERE parent_block = ?1 AND deleted_commit IS NULL",
1460                    &[to_sql(&c("block_id"))],
1461                ))
1462            }),
1463            "parent_type" => Self::require_target(t, Target::Blocks, name).or_else(|| {
1464                Some(
1465                    self.scalar(
1466                        "SELECT type FROM blocks WHERE block_id = ?1",
1467                        &[to_sql(&c("parent_block"))],
1468                    )
1469                    .map(Self::null_if_absent),
1470                )
1471            }),
1472            "has_edge" => {
1473                let pred = js_string(args.first().unwrap_or(&Value::Undefined));
1474                let (src_col, src_val) = if t == Target::Blocks {
1475                    ("src_block", c("block_id"))
1476                } else {
1477                    ("src_doc", c("doc_id"))
1478                };
1479                let r = if args.len() >= 2 {
1480                    self.exists(
1481                        &format!("SELECT 1 FROM edges WHERE {src_col} = ?1 AND predicate = ?2 AND to_commit IS NULL AND dst_node = ?3 LIMIT 1"),
1482                        &[to_sql(&src_val), SqlValue::Text(pred), to_sql(&args[1])],
1483                    )
1484                } else {
1485                    self.exists(
1486                        &format!("SELECT 1 FROM edges WHERE {src_col} = ?1 AND predicate = ?2 AND to_commit IS NULL LIMIT 1"),
1487                        &[to_sql(&src_val), SqlValue::Text(pred)],
1488                    )
1489                };
1490                Some(Self::sql_result(r))
1491            }
1492            "under" => Self::require_target(t, Target::Blocks, name).or_else(|| {
1493                let target = js_string(args.first().unwrap_or(&Value::Undefined));
1494                let ap = col_str(row, "ancestor_path");
1495                Some(Ok(Value::Bool(
1496                    ap.contains(&format!("/{target}/")) || col_str(row, "block_id") == target,
1497                )))
1498            }),
1499            "under_heading" => Self::require_target(t, Target::Blocks, name).or_else(|| {
1500                let text = js_string(args.first().unwrap_or(&Value::Undefined));
1501                let top = match self.top_ordinal(row) {
1502                    Ok(v) => to_sql(&v),
1503                    Err(e) => return Some(Err(e)),
1504                };
1505                Some(Self::sql_result(self.exists(
1506                    "SELECT 1 FROM sections s JOIN blocks hb ON hb.block_id = s.heading_block
1507                     WHERE s.doc_id = ?1 AND lower(hb.text) LIKE '%' || lower(?2) || '%' AND s.first_ordinal <= ?3 AND s.last_ordinal >= ?4 LIMIT 1",
1508                    &[to_sql(&c("doc_id")), SqlValue::Text(text), top.clone(), top],
1509                )))
1510            }),
1511            // `within(t)`: a doc id, else a path in either form (`/texts/*`,
1512            // `texts/*`, `texts/x.md`) matched against the storage path.
1513            "within" => Self::require_target(t, Target::Blocks, name).or_else(|| {
1514                let target = js_string(args.first().unwrap_or(&Value::Undefined));
1515                if target.starts_with("d_") {
1516                    return Some(Ok(Value::Bool(col_str(row, "doc_id") == target)));
1517                }
1518                let target = storage_path(&target).to_owned();
1519                if target.contains('*') {
1520                    let like = glob_to_like(&target, false);
1521                    return Some(Self::sql_result(self.exists(
1522                        "SELECT 1 WHERE ?1 LIKE ?2 ESCAPE '\\'",
1523                        &[SqlValue::Text(col_str(row, "__path")), SqlValue::Text(like)],
1524                    )));
1525                }
1526                Some(Ok(Value::Bool(col_str(row, "__path") == target)))
1527            }),
1528            "under_kind" => Self::require_target(t, Target::Blocks, name).or_else(|| {
1529                let kind = js_string(args.first().unwrap_or(&Value::Undefined));
1530                let ap: Vec<String> = col_str(row, "ancestor_path")
1531                    .split('/')
1532                    .filter(|s| !s.is_empty())
1533                    .map(str::to_owned)
1534                    .collect();
1535                if ap.is_empty() {
1536                    return Some(Ok(Value::Bool(false)));
1537                }
1538                let placeholders: Vec<String> = (1..=ap.len()).map(|i| format!("?{i}")).collect();
1539                let placeholders = placeholders.join(",");
1540                let mut params: Vec<SqlValue> = ap.into_iter().map(SqlValue::Text).collect();
1541                let n = params.len();
1542                params.push(SqlValue::Text(kind));
1543                let r = match args.get(1) {
1544                    Some(v) if !v.is_absent() => {
1545                        let nm = js_string(v);
1546                        params.push(SqlValue::Text(nm.clone()));
1547                        params.push(SqlValue::Text(nm));
1548                        self.exists(
1549                            &format!(
1550                                "SELECT 1 FROM blocks WHERE block_id IN ({placeholders}) AND type = ?{} AND (lower(text) LIKE '%' || lower(?{}) || '%' OR json_extract(attrs,'$.key') = ?{}) LIMIT 1",
1551                                n + 1,
1552                                n + 2,
1553                                n + 3
1554                            ),
1555                            &params,
1556                        )
1557                    }
1558                    _ => self.exists(
1559                        &format!(
1560                            "SELECT 1 FROM blocks WHERE block_id IN ({placeholders}) AND type = ?{} LIMIT 1",
1561                            n + 1
1562                        ),
1563                        &params,
1564                    ),
1565                };
1566                Some(Self::sql_result(r))
1567            }),
1568            "yaml_path" => Self::require_target(t, Target::Blocks, name).or_else(|| {
1569                Some(Ok(Self::key_path(row, &js_string(args.first().unwrap_or(&Value::Undefined)), "yaml")))
1570            }),
1571            "json_pointer" => Self::require_target(t, Target::Blocks, name).or_else(|| {
1572                Some(Ok(Self::key_path(row, &js_string(args.first().unwrap_or(&Value::Undefined)), "json")))
1573            }),
1574            _ => None,
1575        }
1576    }
1577
1578    fn key_path(row: &Value, path: &str, kind: &str) -> Value {
1579        let key = if kind == "json" {
1580            let mut p = path;
1581            p = p.strip_prefix('#').unwrap_or(p);
1582            p = p.strip_prefix('/').unwrap_or(p);
1583            p.split('/').collect::<Vec<_>>().join(".")
1584        } else {
1585            path.to_owned()
1586        };
1587        let leaf = key.rsplit('.').next().unwrap_or("").to_owned();
1588        if !col_str(row, "type").starts_with(&format!("{kind}:")) {
1589            return Value::Bool(false);
1590        }
1591        let k = Self::jattr(row, "key");
1592        Value::Bool(k == Value::Str(leaf) || k == Value::Str(key))
1593    }
1594
1595    fn text_match(&self, t: Target, row: &Value, terms: &str) -> oqx::Result<Value> {
1596        // links and revisions (4.7) have no indexed body: `filter_invalid`.
1597        if matches!(t, Target::Links | Target::Revisions) {
1598            return Err(OqxError::eval(format!(
1599                "text(...) is not available on the {} target",
1600                t.as_str()
1601            )));
1602        }
1603        let m = sanitize_fts_query(terms);
1604        if m.is_empty() {
1605            return Ok(Value::Bool(false));
1606        }
1607        let r = match t {
1608            Target::Docs => self.exists(
1609                "SELECT 1 FROM blocks_fts JOIN blocks b ON b.rowid = blocks_fts.rowid WHERE b.doc_id = ?1 AND blocks_fts MATCH ?2 LIMIT 1",
1610                &[to_sql(col(row, "doc_id")), SqlValue::Text(m)],
1611            ),
1612            Target::Nodes => self.exists(
1613                "SELECT 1 FROM nodes_fts WHERE rowid = (SELECT rowid FROM nodes WHERE node_id = ?1) AND nodes_fts MATCH ?2",
1614                &[to_sql(col(row, "node_id")), SqlValue::Text(m)],
1615            ),
1616            _ => self.exists(
1617                "SELECT 1 FROM blocks_fts WHERE rowid = (SELECT rowid FROM blocks WHERE block_id = ?1) AND blocks_fts MATCH ?2",
1618                &[to_sql(col(row, "block_id")), SqlValue::Text(m)],
1619            ),
1620        };
1621        Self::sql_result(r)
1622    }
1623
1624    /// `recv.matches(pattern[, flags])` exactly as the builtin computes it —
1625    /// an absent receiver is `false` before the pattern is looked at, the
1626    /// pattern is `String(args[0])`, the flags are `args[1]`, then
1627    /// [`CompiledRegex::is_match`] on the receiver's string form — with the
1628    /// compiled pattern held for the run. The builtin's own cache hands out
1629    /// clones of the `regex::Regex`, and a clone starts with an empty
1630    /// search-cache pool, so a scan paid a lazy-DFA cache allocation (and its
1631    /// drop) per row. Flags that are not a string, and patterns that do not
1632    /// compile, are left to the builtin so its errors are reported verbatim.
1633    fn matches_memoized(&self, recv: &Value, args: &[Value]) -> Option<oqx::Result<Value>> {
1634        let flags = match args.get(1) {
1635            None | Some(Value::Undefined) | Some(Value::Null) => None,
1636            Some(Value::Str(s)) => Some(s.clone()),
1637            Some(_) => return None,
1638        };
1639        let Some(subject) = string_form(recv) else {
1640            return Some(Ok(Value::Bool(false)));
1641        };
1642        let pattern = args.first().unwrap_or(&Value::Undefined).to_string();
1643        let key = (pattern, flags);
1644        let mut memo = self.regexes.borrow_mut();
1645        if !memo.contains_key(&key) {
1646            let flags_value = args.get(1).cloned().unwrap_or(Value::Undefined);
1647            match compile_regex(&key.0, &flags_value, RegexDialect::Oqx) {
1648                Ok(re) => {
1649                    memo.insert(key.clone(), re);
1650                }
1651                Err(_) => return None,
1652            }
1653        }
1654        Some(Ok(Value::Bool(memo[&key].is_match(&subject))))
1655    }
1656
1657    fn semantic_score(&self, t: Target, row: &Value, phrase: &str) -> oqx::Result<Value> {
1658        if matches!(t, Target::Nodes | Target::Links | Target::Revisions) {
1659            return Err(OqxError::eval(
1660                "semantic(...) is available on the docs and blocks targets",
1661            ));
1662        }
1663        let Some(resolved) = self.semantic.get(phrase) else {
1664            return Err(OqxError::eval(format!(
1665                "semantic({}) needs an embedding provider; none is configured for this query",
1666                serde_json::Value::String(phrase.to_owned())
1667            )));
1668        };
1669        let vec: oqx::Result<Option<Vec<u8>>> = match t {
1670            Target::Docs => self
1671                .conn
1672                .query_row(
1673                    "SELECT vec FROM doc_embeddings WHERE doc_id = ?1 AND model = ?2",
1674                    rusqlite::params![col_str(row, "doc_id"), resolved.model],
1675                    |r| r.get(0),
1676                )
1677                .optional()
1678                .map_err(sql_err),
1679            // The row for the block's current `(raw_hash, ctx_hash)` only
1680            // (`spec/search` §3, 1.1): a stale context row is never read.
1681            _ => omgbase_store::block_vector(self.conn, &col_str(row, "block_id"), &resolved.model)
1682                .map_err(|e| OqxError::eval(e.to_string())),
1683        };
1684        match vec? {
1685            Some(v) => Ok(Value::Number(cosine_bytes(&v, &resolved.vec))),
1686            None => Ok(Value::Null),
1687        }
1688    }
1689}
1690
1691/// Run `sql` and read every row as a column object (blobs as hex, integers
1692/// and reals as numbers) — the one shape a store row ever has in a query.
1693pub(crate) fn fetch_rows(
1694    conn: &Connection,
1695    sql: &str,
1696    params: &[SqlValue],
1697) -> rusqlite::Result<Vec<Object>> {
1698    let mut stmt = conn.prepare_cached(sql)?;
1699    let names: Vec<String> = stmt
1700        .column_names()
1701        .iter()
1702        .map(|s| (*s).to_owned())
1703        .collect();
1704    let rows = stmt.query_map(params_from_iter(params.iter()), |r| {
1705        // One slot beyond the columns: every row read here is tagged next
1706        // ([`tag_row`]), and the tag must not regrow the entries per row.
1707        let mut o = Object::with_capacity(names.len() + 1);
1708        for (i, name) in names.iter().enumerate() {
1709            o.insert(name.as_str(), sql_value(r.get_ref(i)?));
1710        }
1711        Ok(o)
1712    })?;
1713    rows.collect()
1714}
1715
1716/// Tag a store row with its target so the context resolves it (the
1717/// reference's `tagRows`; the planner hands produced rows back this way).
1718pub(crate) fn tag_row(mut row: Object, t: Target) -> Value {
1719    row.insert(TAG_KEY, Value::Str(t.as_str().to_owned()));
1720    Value::Object(row)
1721}
1722
1723/// [`tag_row`] over a result set.
1724pub(crate) fn tag_rows(rows: Vec<Object>, t: Target) -> Vec<Value> {
1725    rows.into_iter().map(|r| tag_row(r, t)).collect()
1726}
1727
1728/// `cur[seg] = {}` down the path, then the leaf (a scalar in the way is
1729/// replaced by an object; an existing key keeps its position).
1730fn set_nested(out: &mut Object, path: &[&str], leaf: Value) {
1731    let Some((first, rest)) = path.split_first() else {
1732        return;
1733    };
1734    if rest.is_empty() {
1735        out.insert(*first, leaf);
1736        return;
1737    }
1738    let mut child = match out.get(first) {
1739        Some(Value::Object(o)) => o.clone(),
1740        _ => Object::new(),
1741    };
1742    set_nested(&mut child, rest, leaf);
1743    out.insert(*first, Value::Object(child));
1744}
1745
1746/// A `*` glob as a `LIKE` pattern with `ESCAPE '\'`; `escape_backslash`
1747/// also escapes `\` (the list surfaces do, `within` does not).
1748#[must_use]
1749pub fn glob_to_like(glob: &str, escape_backslash: bool) -> String {
1750    let mut out = String::with_capacity(glob.len() + 4);
1751    for ch in glob.chars() {
1752        match ch {
1753            '%' | '_' => {
1754                out.push('\\');
1755                out.push(ch);
1756            }
1757            '\\' if escape_backslash => out.push_str("\\\\"),
1758            '*' => out.push('%'),
1759            c => out.push(c),
1760        }
1761    }
1762    out
1763}
1764
1765impl DataContext for StoreContext<'_> {
1766    fn root(&self, name: &str) -> Value {
1767        if let Some(rr) = self.rows_root.as_ref().filter(|_| name == oqx::ROWS_ROOT) {
1768            let mut slot = rr.rows.borrow_mut();
1769            let rows = if rr.once { slot.take() } else { slot.clone() };
1770            return Value::Array(rows.unwrap_or_default());
1771        }
1772        // The root scope's names (`spec/oqx` §2 step 5 at the root): the five
1773        // lazy scans and `id`, the repository id — so `^docs` / `0^docs` from
1774        // any row is the scan and `^id` / `0^id` the id.
1775        if name == "id" {
1776            return Value::Str(self.repo_id.clone());
1777        }
1778        // A root scan is handed out LAZILY (see `SCAN_KEY`): `to_rows` runs it
1779        // — once per run — and `index_for` probes it without running it.
1780        Target::parse(name).map_or(Value::Undefined, scan_marker)
1781    }
1782
1783    /// The root scope's row (oqx 0.18): the repository, so `^$it` from a
1784    /// top-level row is the root row and `^$it.docs` the docs scan.
1785    fn root_object(&self) -> Value {
1786        self.root_row()
1787    }
1788
1789    fn get(&self, row: &Value, key: &str) -> oqx::Result<Value> {
1790        if row.is_absent() {
1791            return Ok(Value::Undefined);
1792        }
1793        // The root row: `^$it.id` is the repository id, `^$it.<target>` the
1794        // lazy root scan (the same marker `^<target>` / `root(name)` hands out).
1795        if is_root_object(row) {
1796            if key == "id" {
1797                return Ok(Value::Str(self.repo_id.clone()));
1798            }
1799            return Ok(Target::parse(key).map_or(Value::Undefined, scan_marker));
1800        }
1801        let Some(t) = target_of(row) else {
1802            // A plain value (parsed attrs, a property bag, a lifted element).
1803            return Ok(oqx::DefaultContext::read(row, key));
1804        };
1805        // A lazy owner (`LAZY_KEY`) answers its identity, relations and
1806        // properties from the columns it carries; any other key loads the row.
1807        if let Some(full) = self.resolve_lazy(row, t, key)? {
1808            return self.get(&full, key);
1809        }
1810        // `$self` = the current row: the runner rewrites row functions
1811        // (text/under/…) to `$self.fn(…)` so they arrive via `call_method` with
1812        // the row as receiver. Any other `$` name is OQX's (resolved by the
1813        // engine before the row) or unknown — never an omgbase attribute.
1814        if key == "$self" {
1815            return Ok(row.clone());
1816        }
1817        // engine attributes win on collision (the name rule above).
1818        if attributes(t).contains(&key) {
1819            return self.attribute(row, t, key);
1820        }
1821        // self-alias namespaces
1822        match (t, key) {
1823            (Target::Docs, "doc") | (Target::Blocks, "block") | (Target::Nodes, "section") => {
1824                return Ok(row.clone());
1825            }
1826            // from a revision to its document's CURRENT row (4.7), before the
1827            // owning-doc arm the other kinds share.
1828            (Target::Revisions, "doc") => return self.revision_doc(row),
1829            (_, "doc") => return self.owning_doc(row),
1830            (Target::Nodes, "block") => return self.owning_block(row),
1831            (Target::Links, "dst") => return self.destination_doc(row),
1832            _ => {}
1833        }
1834        if let Some(v) = self.relation(row, t, key)? {
1835            return Ok(v);
1836        }
1837        // A bare target name that is not one of this row's relations reads a
1838        // property the row has none of (`spec/surface` §1.1, 2.0): loud, naming
1839        // the root-row spelling. `docs`/`links` never get here (the runner
1840        // refuses them statically); `blocks` on a block or edge row, `nodes`
1841        // on a node or edge row and `revisions` on anything but a document do.
1842        // The reference throws from `get` too.
1843        if let Some(named) = Target::parse(key) {
1844            return Err(OqxError::eval(crate::query::bare_target_message(
1845                named, None,
1846            )));
1847        }
1848        // the author's data.
1849        Ok(match t {
1850            Target::Docs => {
1851                let doc_id = col_str(row, "doc_id");
1852                // The source handles: `data` is the merged authored view
1853                // (frontmatter + inline), the other two one source each;
1854                // `data.<k>` reaches an authored key whose bare name is an
1855                // engine attribute (`data.path`, `data.tags`).
1856                if SOURCE_HANDLES.contains(&key) {
1857                    let source = (key != "data").then_some(key);
1858                    return self.doc_prop_bag(&doc_id, source);
1859                }
1860                return self.doc_prop(&doc_id, key, None);
1861            }
1862            // blocks / nodes: a bare non-structural identifier flattens into
1863            // `attrs.<k>` (the attributes above win on collision); an absent
1864            // key is undefined, matching a doc's missing frontmatter key.
1865            Target::Blocks | Target::Nodes => Self::jattr(row, key),
1866            // closed row shapes (§1.5): no authored data reaches a link or
1867            // revision row — an unknown name is absent (the names pass has
1868            // already refused a tier-3 name statically).
1869            Target::Links | Target::Revisions => Value::Undefined,
1870        })
1871    }
1872
1873    fn to_rows(&self, value: &Value) -> Vec<Value> {
1874        match value {
1875            Value::Undefined | Value::Null => Vec::new(),
1876            Value::Array(a) => a.clone(),
1877            other if is_absent_single(other) => Vec::new(),
1878            other => match scan_of(other) {
1879                Some(t) => self.expand_scan(t),
1880                None => vec![other.clone()],
1881            },
1882        }
1883    }
1884
1885    /// Row position (spec/oqx §3, 0.20): a lazy root scan is a collection; a
1886    /// store row, a lazy owner, the absent-single marker and any other object
1887    /// are one row.
1888    fn is_single(&self, value: &Value) -> bool {
1889        scan_of(value).is_none()
1890    }
1891
1892    /// A lazy root-scan marker observed as a VALUE is its rows (read once per
1893    /// run); the absent-single marker is absent; everything else is itself. A
1894    /// store row is an object with several columns and the markers have exactly
1895    /// one key, so the common case is one length check.
1896    fn materialize(&self, value: Value) -> Value {
1897        if value.as_object().is_some_and(|o| o.len() == 1) {
1898            if let Some(t) = scan_of(&value) {
1899                return Value::Array(self.expand_scan(t));
1900            }
1901            if is_absent_single(&value) {
1902                return Value::Undefined;
1903            }
1904        }
1905        value
1906    }
1907
1908    fn index_for(&self, collection: &Value, path: &[String]) -> Option<Rc<dyn RowIndex + '_>> {
1909        crate::store_index::index_for(self, scan_of(collection)?, path)
1910    }
1911
1912    fn identity(&self, row: &Value) -> Value {
1913        match target_of(row) {
1914            Some(Target::Docs) => col(row, "doc_id").clone(),
1915            Some(Target::Blocks) => col(row, "block_id").clone(),
1916            Some(Target::Nodes) => col(row, "node_id").clone(),
1917            Some(Target::Links) => col(row, "edge_id").clone(),
1918            Some(Target::Revisions) => col(row, "rev_id").clone(),
1919            None => row.clone(),
1920        }
1921    }
1922
1923    fn call_function(&self, name: &str, args: &[Value]) -> Option<oqx::Result<Value>> {
1924        // `size(^docs)`, `list(…)`, `has(…)`: the engine has materialized a
1925        // lazy scan argument into its rows before the call.
1926        if name == "refs" {
1927            return Some(self.refs(args.first().unwrap_or(&Value::Undefined)));
1928        }
1929        if name == "range" {
1930            let x = args.first().unwrap_or(&Value::Undefined);
1931            return Some(Ok(match x {
1932                Value::Range(_) => x.clone(),
1933                Value::Str(s) => match omgbase_properties::detect_range(s) {
1934                    Some(r) => {
1935                        let b = |b: &Bound| match b {
1936                            Bound::Open => Value::Undefined,
1937                            Bound::Num(n) => Value::Number(*n),
1938                            Bound::Iso(s) => Value::Str(s.clone()),
1939                        };
1940                        Value::from(make_range(b(&r.lo), b(&r.hi), r.exclusive_end))
1941                    }
1942                    None => Value::Null,
1943                },
1944                _ => Value::Null,
1945            }));
1946        }
1947        builtin_function(name, args)
1948    }
1949
1950    fn call_method(&self, name: &str, recv: &Value, args: &[Value]) -> Option<oqx::Result<Value>> {
1951        // `^docs.size()`: the receiver, a value, is materialized by the
1952        // engine before the call.
1953        if let Some(t) = target_of(recv) {
1954            // A row function reads the row's columns: a lazy owner is loaded first.
1955            let full;
1956            let recv = if is_lazy_owner(recv) {
1957                let id_col = if t == Target::Docs {
1958                    "doc_id"
1959                } else {
1960                    "block_id"
1961                };
1962                match self.load_owner(t, &col_str(recv, id_col)) {
1963                    Ok(Some(v)) => {
1964                        full = v;
1965                        &full
1966                    }
1967                    Ok(None) => recv,
1968                    Err(e) => return Some(Err(e)),
1969                }
1970            } else {
1971                recv
1972            };
1973            if let Some(r) = self.row_method(name, recv, t, args) {
1974                return Some(r);
1975            }
1976        } else if matches!(
1977            name,
1978            "text"
1979                | "semantic"
1980                | "under"
1981                | "under_heading"
1982                | "within"
1983                | "under_kind"
1984                | "yaml_path"
1985                | "json_pointer"
1986                | "has_edge"
1987                | "has_anchor"
1988                | "child_count"
1989                | "parent_type"
1990        ) {
1991            return Self::filter_invalid(format!("{name}() needs a docs/blocks/nodes/links row"));
1992        }
1993        if name == "matches" {
1994            if let Some(r) = self.matches_memoized(recv, args) {
1995                return Some(r);
1996            }
1997        }
1998        builtin_method_with(RegexDialect::Oqx, name, recv, args)
1999    }
2000}
2001
2002#[cfg(test)]
2003mod tests {
2004    use super::*;
2005
2006    #[test]
2007    fn glob_to_like_escapes() {
2008        assert_eq!(glob_to_like("a*/b_%", true), "a%/b\\_\\%");
2009        assert_eq!(glob_to_like("a\\b*", true), "a\\\\b%");
2010        assert_eq!(glob_to_like("a\\b*", false), "a\\b%");
2011    }
2012
2013    #[test]
2014    fn rows_surfacing_as_values_render_id_and_path() {
2015        // §1.4 (1.2, keys renamed in 3.0): a tagged store row anywhere in a
2016        // value tree is `{ id, path }`; untagged records keep their keys,
2017        // minus the tag.
2018        let mut node = Object::new();
2019        node.insert("node_id", Value::Str("n_1".into()));
2020        node.insert("attrs", Value::Str("{\"checked\":true}".into()));
2021        node.insert("__path", Value::Str("a.md".into()));
2022        let mut doc = Object::new();
2023        doc.insert("doc_id", Value::Str("d_0".into()));
2024        doc.insert("path", Value::Str("a.md".into()));
2025        doc.insert("blob", Value::Str("ff".into()));
2026        let mut record = Object::new();
2027        record.insert(TAG_KEY, Value::Str("junk".into()));
2028        record.insert(
2029            "tasks",
2030            Value::Array(vec![
2031                tag_row(node, Target::Nodes),
2032                tag_row(doc, Target::Docs),
2033            ]),
2034        );
2035        let out = render_row_values(Value::Object(record));
2036        let o = out.as_object().unwrap();
2037        assert!(o.get(TAG_KEY).is_none());
2038        let tasks = o.get("tasks").unwrap().as_array().unwrap();
2039        let keys = |v: &Value| -> Vec<String> {
2040            v.as_object()
2041                .unwrap()
2042                .iter()
2043                .map(|(k, _)| k.to_owned())
2044                .collect()
2045        };
2046        assert_eq!(keys(&tasks[0]), ["id", "path"]);
2047        assert_eq!(
2048            tasks[0].as_object().unwrap().get("id"),
2049            Some(&Value::Str("n_1".into()))
2050        );
2051        assert_eq!(
2052            tasks[0].as_object().unwrap().get("path"),
2053            Some(&Value::Str("/a.md".into()))
2054        );
2055        assert_eq!(keys(&tasks[1]), ["id", "path"]);
2056        assert_eq!(
2057            tasks[1].as_object().unwrap().get("id"),
2058            Some(&Value::Str("d_0".into()))
2059        );
2060        // An id column that is not a string still renders as its string form.
2061        let mut edge = Object::new();
2062        edge.insert("edge_id", Value::Number(7.0));
2063        let e = render_row_values(tag_row(edge, Target::Links));
2064        assert_eq!(
2065            e.as_object().unwrap().get("id"),
2066            Some(&Value::Str("7".into()))
2067        );
2068        assert_eq!(
2069            e.as_object().unwrap().get("path"),
2070            Some(&Value::Str(String::new()))
2071        );
2072    }
2073
2074    #[test]
2075    fn nested_property_objects_rebuild() {
2076        let mut o = Object::new();
2077        set_nested(&mut o, &["a", "b"], Value::Number(1.0));
2078        set_nested(&mut o, &["a", "c"], Value::Number(2.0));
2079        set_nested(&mut o, &["d"], Value::Str("x".into()));
2080        let a = o.get("a").unwrap().as_object().unwrap();
2081        assert_eq!(a.get("b"), Some(&Value::Number(1.0)));
2082        assert_eq!(a.get("c"), Some(&Value::Number(2.0)));
2083        assert_eq!(o.get("d"), Some(&Value::Str("x".into())));
2084        // A scalar in the way is replaced by an object.
2085        set_nested(&mut o, &["d", "e"], Value::Bool(true));
2086        assert!(o.get("d").unwrap().as_object().is_some());
2087    }
2088
2089    #[test]
2090    fn json_and_sql_bridges() {
2091        assert_eq!(
2092            parse_json(&Value::Str("{\"a\":1}".into()))
2093                .as_object()
2094                .unwrap()
2095                .get("a"),
2096            Some(&Value::Number(1.0))
2097        );
2098        assert_eq!(
2099            parse_json(&Value::Str("nope".into())),
2100            Value::Str("nope".into())
2101        );
2102        assert_eq!(parse_json(&Value::Null), Value::Undefined);
2103        assert_eq!(arg_or_empty(&[], 0), "");
2104        assert_eq!(arg_or_empty(&[Value::Number(2.0)], 0), "2");
2105    }
2106}