Skip to main content

nedb_engine/
nql.rs

1// SPDX-FileCopyrightText: 2026 INTERCHAINED LLC
2// SPDX-License-Identifier: BUSL-1.1
3// NEDB · © 2026 INTERCHAINED LLC × Eth-Interchained × Vex (Claude Opus 5)
4
5//! NQL (NEDB Query Language) parser and executor for v2 DAG storage.
6//!
7//! Grammar:
8//!   FROM coll
9//!     [AS OF seq]
10//!     [VALID AS OF "date"]
11//!     [WHERE <predicate>]
12//!     [SEARCH "text"]
13//!     [ORDER BY field [ASC|DESC]]
14//!     [LIMIT n]
15//!     [GROUP BY field COUNT|SUM|AVG|MIN|MAX]
16//!     [TRACE caused_by [REVERSE]]
17//!
18//! where <predicate> is a full boolean expression:
19//!
20//!   <predicate> := <or>
21//!   <or>        := <and> [OR <and>]*
22//!   <and>       := <not> [AND <not>]*
23//!   <not>       := [NOT] <primary>
24//!   <primary>   := "(" <predicate> ")" | <comparison>
25//!   <comparison>:= field ( = | != | > | < | >= | <= ) value
26//!                | field [NOT] IN "(" value [, value]* ")"
27//!                | field [NOT] BETWEEN value AND value
28//!                | field [NOT] LIKE|ILIKE "pattern"
29//!                | field IS [NOT] NULL
30//!
31//! Until 3.3.0 the predicate surface was six operators wide (= != > < >= <=)
32//! joined by an implicit AND, with no grouping, no negation and no set/range/
33//! pattern tests. Every one of those is table stakes in SQL, and their absence
34//! is the single most visible gap against a SQL engine: the queries people
35//! actually type (`status IN ('open','pending')`, `height BETWEEN 100 AND 200`,
36//! `name LIKE 'ac%'`) had to be decomposed by hand or filtered client-side.
37//!
38//! NOTE ON STRICTNESS. The old parser ended its clause loop with
39//! `_ => { self.advance(); }` — "skip unrecognised". That is the same defect
40//! class as a swallowed write error: a query containing a clause the engine
41//! does not implement did not fail, it silently returned the results of a
42//! DIFFERENT query. `FROM x WHERE a = 1 OFFSET 5` dropped both tokens and
43//! answered without the offset; a misspelled `ORDRE BY height` answered
44//! unsorted. Unknown tokens are now a parse error. This is deliberately
45//! breaking for queries that were already being silently misread — there was
46//! no correct behaviour to preserve.
47
48use std::collections::HashMap;
49use anyhow::{bail, Result};
50use serde_json::{json, Value};
51
52use crate::db::Db;
53use crate::index::OrderedValue;
54use crate::store::Node;
55
56// ── Token types ──────────────────────────────────────────────────────────────
57
58#[derive(Debug, Clone, PartialEq)]
59enum Tok {
60    /// A reserved word: (UPPERCASED for matching, RAW as the user spelled it).
61    ///
62    /// The raw spelling has to survive. Field positions accept a keyword as a
63    /// field name -- a document may legitimately have a field called `count`,
64    /// `min`, `value` or `status` -- and using the uppercased form there looks
65    /// up a key that does not exist. That made `HAVING count > 1` and
66    /// `ORDER BY count DESC` silently match nothing, because they searched the
67    /// row for "COUNT".
68    Kw(String, String),
69    Ident(String),  // field name or collection name (lowercase/mixed)
70    Str(String),    // "quoted string"
71    Num(f64),       // numeric literal
72    Op(String),     // = != > < >= <=
73    Punct(char),    // ( ) ,
74    Eof,
75}
76
77struct Lexer<'a> {
78    src:  &'a str,
79    pos:  usize,
80}
81
82impl<'a> Lexer<'a> {
83    fn new(src: &'a str) -> Self { Self { src, pos: 0 } }
84
85    fn peek_char(&self) -> Option<char> { self.src[self.pos..].chars().next() }
86
87    fn skip_ws(&mut self) {
88        while let Some(c) = self.peek_char() {
89            if c.is_whitespace() { self.pos += c.len_utf8(); } else { break; }
90        }
91    }
92
93    fn next_tok(&mut self) -> Tok {
94        self.skip_ws();
95        if self.pos >= self.src.len() { return Tok::Eof; }
96
97        let c = self.peek_char().unwrap();
98
99        // Quoted string.
100        //
101        // A backslash escapes a following double-quote (\" -> a literal " that
102        // does NOT end the string). This is purely additive: a literal quote
103        // was previously impossible to express — the first " always closed the
104        // string — so no existing query can rely on the old meaning of \" and
105        // nothing breaks. Every OTHER backslash stays literal, so raw-backslash
106        // values (e.g. a Windows path) keep matching exactly as before; a
107        // regression test pins that. (A fully C-style scheme where \\ -> \
108        // would instead change the meaning of every existing backslash query,
109        // so it is deliberately NOT done here.)
110        if c == '"' {
111            self.pos += 1;
112            let mut s = String::new();
113            while let Some(ch) = self.peek_char() {
114                if ch == '"' {
115                    break;
116                }
117                if ch == '\\' {
118                    // Look at the next char: only \" collapses to ". A trailing
119                    // backslash (nothing after it) or \x for any other x stays
120                    // a literal backslash, preserving prior behavior.
121                    let next = self.src[self.pos + 1..].chars().next();
122                    if next == Some('"') {
123                        s.push('"');
124                        self.pos += 1 + 1; // consume the backslash and the quote
125                        continue;
126                    }
127                }
128                s.push(ch);
129                self.pos += ch.len_utf8();
130            }
131            if self.peek_char() == Some('"') {
132                self.pos += 1;
133            }
134            return Tok::Str(s);
135        }
136
137        // Three-char operators: the case-insensitive regex negation `!~*`.
138        // Longest match FIRST — checked before `!~` and before `!=`, or `!~*`
139        // would tokenise as `!~` followed by a stray `*`.
140        if self.pos + 2 < self.src.len() && &self.src[self.pos..self.pos + 3] == "!~*" {
141            self.pos += 3;
142            return Tok::Op("!~*".to_string());
143        }
144
145        // Two-char operators
146        if self.pos + 1 < self.src.len() {
147            let two = &self.src[self.pos..self.pos+2];
148            if matches!(two, "!=" | ">=" | "<=" | "!~" | "~*") {
149                self.pos += 2;
150                return Tok::Op(two.to_string());
151            }
152        }
153
154        // One-char operators
155        if matches!(c, '=' | '>' | '<' | '~') {
156            self.pos += 1;
157            return Tok::Op(c.to_string());
158        }
159
160        // Punctuation: grouping for boolean predicates and IN-list separators.
161        // These previously fell through to "skip unknown char", so `(`, `)` and
162        // `,` were invisible to the parser — which is why the grammar could not
163        // express either grouping or a value list.
164        if matches!(c, '(' | ')' | ',') {
165            self.pos += 1;
166            return Tok::Punct(c);
167        }
168
169        // Number
170        if c.is_ascii_digit() || (c == '-' && self.src[self.pos+1..].starts_with(|d: char| d.is_ascii_digit())) {
171            let start = self.pos;
172            if c == '-' { self.pos += 1; }
173            while let Some(d) = self.peek_char() {
174                if d.is_ascii_digit() || d == '.' { self.pos += 1; } else { break; }
175            }
176            let n: f64 = self.src[start..self.pos].parse().unwrap_or(0.0);
177            return Tok::Num(n);
178        }
179
180        // Keyword or identifier
181        if c.is_alphabetic() || c == '_' {
182            let start = self.pos;
183            while let Some(ch) = self.peek_char() {
184                if ch.is_alphanumeric() || ch == '_' || ch == '.' || ch == ':' {
185                    self.pos += ch.len_utf8();
186                } else { break; }
187            }
188            let word = &self.src[start..self.pos];
189            let upper = word.to_uppercase();
190            let keywords = ["FROM","AS","OF","VALID","WHERE","AND","OR","ORDER","BY",
191                            "ASC","DESC","LIMIT","OFFSET","GROUP","HAVING",
192                            "COUNT","SUM","AVG","MIN","MAX",
193                            "TRACE","TRAVERSE","REVERSE","SEARCH","NOT","NULL","TRUE","FALSE",
194                            "IN","BETWEEN","LIKE","ILIKE","IS"];
195            if keywords.contains(&upper.as_str()) {
196                return Tok::Kw(upper, word.to_string());
197            }
198            return Tok::Ident(word.to_string());
199        }
200
201        // Skip unknown char
202        self.pos += c.len_utf8();
203        self.next_tok()
204    }
205
206    fn tokenize(&mut self) -> Vec<Tok> {
207        let mut toks = vec![];
208        loop {
209            let t = self.next_tok();
210            if t == Tok::Eof { break; }
211            toks.push(t);
212        }
213        toks
214    }
215}
216
217// ── AST ──────────────────────────────────────────────────────────────────────
218
219/// A boolean predicate tree.
220///
221/// The old representation was `Vec<WhereClause>` evaluated with `.all()`, which
222/// can only ever express a conjunction of comparisons. A tree is required for
223/// OR, for NOT, and for parenthesised grouping — `WHERE (a = 1 OR b = 2) AND
224/// c != 3` has no encoding as a flat list.
225#[derive(Debug, Clone)]
226pub enum Pred {
227    /// field <op> value, for op in = != > < >= <=
228    Cmp { field: String, op: String, value: Value },
229    /// field [NOT] IN (v1, v2, ...)
230    In { field: String, values: Vec<Value>, negated: bool },
231    /// field [NOT] BETWEEN low AND high — inclusive on both ends, as in SQL.
232    Between { field: String, low: Value, high: Value, negated: bool },
233    /// field [NOT] LIKE "pat" — SQL wildcards: % = any run, _ = any one char.
234    /// `ci` is set by ILIKE (case-insensitive).
235    Like { field: String, pattern: String, negated: bool, ci: bool },
236    /// `field ~ "pat"` / `field !~ "pat"` — POSIX regex match, over a
237    /// DOCUMENTED SUBSET. `ci` is set by `~*` / `!~*`.
238    ///
239    /// Exists because Postgres catalogue introspection needs it: `psql`'s
240    /// `\dn` filters with `nspname !~ '^pg_'`, and `\dt` with
241    /// `nspname !~ '^pg_toast'`. Without the operator those queries cannot
242    /// run at all.
243    ///
244    /// The subset is `^`, `$`, `.`, and literal text — which is everything
245    /// those queries actually use. A pattern containing any other
246    /// metacharacter is REFUSED with an error naming it, rather than matched
247    /// approximately. Approximate regex matching on a catalogue filter would
248    /// silently include or exclude schemas, and a wrong schema list looks
249    /// exactly like a correct one.
250    ///
251    /// Deliberately no `regex` crate: it would add a dependency tree to an
252    /// engine whose small footprint is a selling point, to serve two anchored
253    /// prefix patterns.
254    Regex { field: String, pattern: String, negated: bool, ci: bool },
255    /// field IS [NOT] NULL — true when the field is JSON null OR absent.
256    IsNull { field: String, negated: bool },
257    And(Vec<Pred>),
258    Or(Vec<Pred>),
259    Not(Box<Pred>),
260}
261
262#[derive(Debug, Clone, PartialEq)]
263pub enum GroupAgg { Count, Sum, Avg, Min, Max }
264
265impl GroupAgg {
266    fn name(&self) -> &'static str {
267        match self {
268            GroupAgg::Count => "count", GroupAgg::Sum => "sum",
269            GroupAgg::Avg   => "avg",   GroupAgg::Min => "min",
270            GroupAgg::Max   => "max",
271        }
272    }
273}
274
275/// One `ORDER BY` key. A list of these replaces the old single
276/// `Option<String>` + `bool` pair, because `ORDER BY status, fee DESC` — sort
277/// by one column then break ties with another — has no encoding as a single
278/// field plus a single direction.
279#[derive(Debug, Clone, PartialEq)]
280pub struct OrderKey {
281    pub field: String,
282    pub desc:  bool,
283}
284
285/// An aggregate, grouped or ungrouped.
286///
287/// `group_field: None` is a whole-result aggregate — `FROM t COUNT`,
288/// `FROM t SUM fee` — which returns exactly one row. That was previously
289/// inexpressible: the aggregate keywords only existed after `GROUP BY`, so
290/// "how many rows match this?" had to fetch every row and count client-side.
291#[derive(Debug, Clone)]
292pub struct Aggregate {
293    pub group_field: Option<String>,
294    pub agg:         GroupAgg,
295    /// The field to aggregate. None for COUNT, which needs no target.
296    pub agg_field:   Option<String>,
297}
298
299#[derive(Debug, Clone)]
300pub struct Query {
301    pub coll:       String,
302    pub as_of:      Option<u64>,
303    pub valid_as_of: Option<String>,
304    pub where_:     Option<Pred>,
305    pub search:     Option<String>,
306    pub order_by:   Vec<OrderKey>,
307    pub limit:      Option<usize>,
308    pub offset:     Option<usize>,
309    pub aggregate:  Option<Aggregate>,
310    /// `HAVING <predicate>` — filters the AGGREGATED rows, so it can test
311    /// `count`, `sum_fee`, or the group key itself. Distinct from WHERE, which
312    /// filters input rows before they are grouped.
313    pub having:     Option<Pred>,
314    pub trace:      Option<String>,     // edge type (usually "caused_by")
315    pub trace_rev:  bool,
316    pub traverse:   Option<String>,     // named relation for TRAVERSE rel
317}
318
319// ── Parser ────────────────────────────────────────────────────────────────────
320
321struct Parser { toks: Vec<Tok>, pos: usize }
322
323impl Parser {
324    fn new(toks: Vec<Tok>) -> Self { Self { toks, pos: 0 } }
325
326    fn peek(&self) -> &Tok { self.toks.get(self.pos).unwrap_or(&Tok::Eof) }
327    fn advance(&mut self) -> Tok { let t = self.peek().clone(); self.pos += 1; t }
328
329    fn expect_kw(&mut self, kw: &str) -> Result<()> {
330        match self.advance() {
331            Tok::Kw(k, _) if k == kw => Ok(()),
332            other => bail!("expected keyword {}, got {:?}", kw, other),
333        }
334    }
335
336    /// Parse a literal.
337    ///
338    /// Returns `Result` rather than defaulting to `Value::Null`: the old arm
339    /// `_ => Value::Null` turned a syntax error into a comparison against null,
340    /// so `WHERE height > )` quietly answered "nothing is greater than null"
341    /// instead of reporting a malformed query.
342    fn parse_value(&mut self) -> Result<Value> {
343        Ok(match self.advance() {
344            Tok::Str(s)  => Value::String(s),
345            Tok::Num(n)  => json!(n),
346            Tok::Kw(k, _) if k == "NULL"  => Value::Null,
347            Tok::Kw(k, _) if k == "TRUE"  => Value::Bool(true),
348            Tok::Kw(k, _) if k == "FALSE" => Value::Bool(false),
349            Tok::Ident(s) => Value::String(s),
350            other => bail!("expected a value (string, number, TRUE, FALSE or NULL), got {:?}", other),
351        })
352    }
353
354    fn peek_kw(&self, kw: &str) -> bool {
355        matches!(self.peek(), Tok::Kw(k, _) if k == kw)
356    }
357
358    fn eat_kw(&mut self, kw: &str) -> bool {
359        if self.peek_kw(kw) { self.advance(); true } else { false }
360    }
361
362    fn expect_punct(&mut self, c: char) -> Result<()> {
363        match self.advance() {
364            Tok::Punct(p) if p == c => Ok(()),
365            other => bail!("expected '{}', got {:?}", c, other),
366        }
367    }
368
369    fn parse_agg_kw(&mut self) -> Result<GroupAgg> {
370        Ok(match self.advance() {
371            Tok::Kw(a, _) if a == "COUNT" => GroupAgg::Count,
372            Tok::Kw(a, _) if a == "SUM"   => GroupAgg::Sum,
373            Tok::Kw(a, _) if a == "AVG"   => GroupAgg::Avg,
374            Tok::Kw(a, _) if a == "MIN"   => GroupAgg::Min,
375            Tok::Kw(a, _) if a == "MAX"   => GroupAgg::Max,
376            other => bail!("expected an aggregate (COUNT/SUM/AVG/MIN/MAX), got {:?}", other),
377        })
378    }
379
380    fn parse_field(&mut self, ctx: &str) -> Result<String> {
381        match self.advance() {
382            Tok::Ident(s) | Tok::Kw(_, s) => Ok(s),
383            other => bail!("{}: expected field name, got {:?}", ctx, other),
384        }
385    }
386
387    // ── Predicate grammar: OR binds loosest, then AND, then NOT ──────────────
388
389    fn parse_pred(&mut self) -> Result<Pred> { self.parse_or() }
390
391    fn parse_or(&mut self) -> Result<Pred> {
392        let mut terms = vec![self.parse_and()?];
393        while self.eat_kw("OR") {
394            terms.push(self.parse_and()?);
395        }
396        Ok(if terms.len() == 1 { terms.pop().unwrap() } else { Pred::Or(terms) })
397    }
398
399    fn parse_and(&mut self) -> Result<Pred> {
400        let mut terms = vec![self.parse_not()?];
401        while self.peek_kw("AND") {
402            // `BETWEEN low AND high` owns its AND — it is consumed inside
403            // parse_comparison, so any AND reaching here is a real conjunction.
404            self.advance();
405            terms.push(self.parse_not()?);
406        }
407        Ok(if terms.len() == 1 { terms.pop().unwrap() } else { Pred::And(terms) })
408    }
409
410    fn parse_not(&mut self) -> Result<Pred> {
411        if self.eat_kw("NOT") {
412            return Ok(Pred::Not(Box::new(self.parse_not()?)));
413        }
414        self.parse_primary()
415    }
416
417    fn parse_primary(&mut self) -> Result<Pred> {
418        if matches!(self.peek(), Tok::Punct('(')) {
419            self.advance();
420            let inner = self.parse_pred()?;
421            self.expect_punct(')')?;
422            return Ok(inner);
423        }
424        self.parse_comparison()
425    }
426
427    fn parse_comparison(&mut self) -> Result<Pred> {
428        let field = self.parse_field("WHERE")?;
429
430        // field IS [NOT] NULL
431        if self.eat_kw("IS") {
432            let negated = self.eat_kw("NOT");
433            if !self.eat_kw("NULL") {
434                bail!("WHERE: expected NULL after IS{}", if negated { " NOT" } else { "" });
435            }
436            return Ok(Pred::IsNull { field, negated });
437        }
438
439        // A leading NOT applies to the operator that follows: IN / BETWEEN / LIKE.
440        let negated = self.eat_kw("NOT");
441
442        if self.eat_kw("IN") {
443            self.expect_punct('(')?;
444            let mut values = vec![];
445            loop {
446                values.push(self.parse_value()?);
447                if matches!(self.peek(), Tok::Punct(',')) { self.advance(); continue; }
448                break;
449            }
450            self.expect_punct(')')?;
451            if values.is_empty() {
452                bail!("WHERE: IN () needs at least one value");
453            }
454            return Ok(Pred::In { field, values, negated });
455        }
456
457        if self.eat_kw("BETWEEN") {
458            let low = self.parse_value()?;
459            if !self.eat_kw("AND") {
460                bail!("WHERE: BETWEEN expects AND between its bounds");
461            }
462            let high = self.parse_value()?;
463            return Ok(Pred::Between { field, low, high, negated });
464        }
465
466        let ci = self.peek_kw("ILIKE");
467        if ci || self.peek_kw("LIKE") {
468            self.advance();
469            let pattern = match self.advance() {
470                Tok::Str(s) => s,
471                Tok::Ident(s) => s,
472                other => bail!("WHERE: LIKE expects a pattern string, got {:?}", other),
473            };
474            return Ok(Pred::Like { field, pattern, negated, ci });
475        }
476
477        if negated {
478            bail!("WHERE: NOT must be followed by IN, BETWEEN, LIKE or ILIKE \
479                   (use `NOT (field = value)` or `field != value` to negate a comparison)");
480        }
481
482        let op = match self.advance() {
483            Tok::Op(s) => s,
484            other => bail!("WHERE: expected operator, got {:?}", other),
485        };
486
487        // `~` / `~*` / `!~` / `!~*` — POSIX regex match. Its argument is a
488        // PATTERN, not a value, so it is taken as text and validated here
489        // rather than passed through `parse_value` (which would happily
490        // interpret `^1` as something numeric).
491        if matches!(op.as_str(), "~" | "~*" | "!~" | "!~*") {
492            let pattern = match self.advance() {
493                Tok::Str(s) => s,
494                Tok::Ident(s) => s,
495                other => bail!("WHERE: {} expects a pattern string, got {:?}", op, other),
496            };
497            // Refuse an unsupported metacharacter HERE, at parse time, so the
498            // caller learns at the point of the mistake instead of receiving a
499            // confidently wrong row set.
500            if let Some(why) = regex_error(&pattern) {
501                bail!("WHERE: {} — in {:?}. The supported subset is ^ $ . | ( ) \
502                       [ ] * + ? and literal text. Matching the rest approximately \
503                       would silently include or exclude rows, so it is refused \
504                       instead", why, pattern);
505            }
506            return Ok(Pred::Regex {
507                field,
508                pattern,
509                negated: op.starts_with('!'),
510                ci: op.ends_with('*'),
511            });
512        }
513
514        let value = self.parse_value()?;
515        Ok(Pred::Cmp { field, op, value })
516    }
517
518    fn parse(&mut self) -> Result<Query> {
519        self.expect_kw("FROM")?;
520        let coll = match self.advance() {
521            Tok::Ident(s) | Tok::Kw(_, s) => s,
522            other => bail!("expected collection name, got {:?}", other),
523        };
524
525        let mut q = Query {
526            coll, as_of: None, valid_as_of: None,
527            where_: None, search: None,
528            order_by: vec![],
529            limit: None, offset: None,
530            aggregate: None, having: None,
531            trace: None, trace_rev: false,
532            traverse: None,
533        };
534
535        loop {
536            match self.peek() {
537                Tok::Eof => break,
538
539                Tok::Kw(k, _) if k == "AS" => {
540                    self.advance();
541                    self.expect_kw("OF")?;
542                    match self.advance() {
543                        Tok::Num(n) => q.as_of = Some(n as u64),
544                        other => bail!("AS OF expects sequence number, got {:?}", other),
545                    }
546                }
547
548                Tok::Kw(k, _) if k == "VALID" => {
549                    self.advance();
550                    self.expect_kw("AS")?;
551                    self.expect_kw("OF")?;
552                    match self.advance() {
553                        Tok::Str(s) => q.valid_as_of = Some(s),
554                        other => bail!("VALID AS OF expects date string, got {:?}", other),
555                    }
556                }
557
558                Tok::Kw(k, _) if k == "WHERE" => {
559                    self.advance();
560                    let pred = self.parse_pred()?;
561                    // Repeating WHERE is a conjunction, matching the old
562                    // behaviour where every clause was ANDed together.
563                    q.where_ = Some(match q.where_.take() {
564                        None => pred,
565                        Some(prev) => Pred::And(vec![prev, pred]),
566                    });
567                }
568
569                Tok::Kw(k, _) if k == "SEARCH" => {
570                    self.advance();
571                    match self.advance() {
572                        Tok::Str(s) => q.search = Some(s),
573                        other => bail!("SEARCH expects quoted string, got {:?}", other),
574                    }
575                }
576
577                Tok::Kw(k, _) if k == "ORDER" => {
578                    self.advance();
579                    self.expect_kw("BY")?;
580                    // Comma-separated sort keys, each with its own direction:
581                    // ORDER BY status, fee DESC
582                    loop {
583                        let field = self.parse_field("ORDER BY")?;
584                        // ASC is a real keyword now. It used to lex as an Ident
585                        // and survive only because the clause loop silently
586                        // skipped tokens it did not recognise.
587                        let desc = if self.eat_kw("DESC") {
588                            true
589                        } else {
590                            self.eat_kw("ASC");
591                            false
592                        };
593                        q.order_by.push(OrderKey { field, desc });
594                        if matches!(self.peek(), Tok::Punct(',')) { self.advance(); continue; }
595                        break;
596                    }
597                }
598
599                Tok::Kw(k, _) if k == "LIMIT" => {
600                    self.advance();
601                    match self.advance() {
602                        Tok::Num(n) if n >= 0.0 => q.limit = Some(n as usize),
603                        other => bail!("LIMIT expects a non-negative number, got {:?}", other),
604                    }
605                }
606
607                Tok::Kw(k, _) if k == "OFFSET" => {
608                    self.advance();
609                    match self.advance() {
610                        Tok::Num(n) if n >= 0.0 => q.offset = Some(n as usize),
611                        other => bail!("OFFSET expects a non-negative number, got {:?}", other),
612                    }
613                }
614
615                Tok::Kw(k, _) if k == "HAVING" => {
616                    self.advance();
617                    let pred = self.parse_pred()?;
618                    q.having = Some(match q.having.take() {
619                        None => pred,
620                        Some(prev) => Pred::And(vec![prev, pred]),
621                    });
622                }
623
624                // A bare aggregate with no GROUP BY: `FROM t COUNT`,
625                // `FROM t SUM fee`. Returns exactly one row.
626                Tok::Kw(k, _) if matches!(k.as_str(), "COUNT" | "SUM" | "AVG" | "MIN" | "MAX") => {
627                    let agg = self.parse_agg_kw()?;
628                    let agg_field = match agg {
629                        GroupAgg::Count => None,
630                        _ => Some(self.parse_field("aggregate")?),
631                    };
632                    if q.aggregate.is_some() {
633                        bail!("only one aggregate per query");
634                    }
635                    q.aggregate = Some(Aggregate { group_field: None, agg, agg_field });
636                }
637
638                Tok::Kw(k, _) if k == "GROUP" => {
639                    self.advance();
640                    self.expect_kw("BY")?;
641                    let field = match self.advance() {
642                        Tok::Ident(s) | Tok::Kw(_, s) => s,
643                        other => bail!("GROUP BY: expected field, got {:?}", other),
644                    };
645                    // The aggregate is OPTIONAL, matching the Python reference
646                    // (query.py): `GROUP BY field` on its own yields per-group
647                    // counts. Rust previously REQUIRED the keyword, so a bare
648                    // GROUP BY was a parse error here and valid there.
649                    let agg = if matches!(self.peek(),
650                        Tok::Kw(a, _) if matches!(a.as_str(), "COUNT"|"SUM"|"AVG"|"MIN"|"MAX"))
651                    {
652                        self.parse_agg_kw()?
653                    } else {
654                        GroupAgg::Count
655                    };
656                    // SUM/AVG/MIN/MAX take the field to aggregate. Without it
657                    // the executor fell back to aggregating the GROUP BY field
658                    // itself, so `GROUP BY cat MAX price` reported the max
659                    // *cat* — and since a non-numeric value coerced to 1.0,
660                    // every group answered 1. The target field was lexed and
661                    // then silently dropped by the unknown-token skip.
662                    let agg_field = match agg {
663                        GroupAgg::Count => None,
664                        _ => Some(self.parse_field("GROUP BY aggregate")?),
665                    };
666                    if q.aggregate.is_some() {
667                        bail!("only one aggregate per query");
668                    }
669                    q.aggregate = Some(Aggregate {
670                        group_field: Some(field), agg, agg_field,
671                    });
672                }
673
674                Tok::Kw(k, _) if k == "TRACE" => {
675                    self.advance();
676                    let edge = match self.advance() {
677                        Tok::Ident(s) | Tok::Kw(_, s) => s,
678                        other => bail!("TRACE: expected edge type, got {:?}", other),
679                    };
680                    q.trace = Some(edge);
681                    if let Tok::Kw(k, _) = self.peek() {
682                        if k == "REVERSE" { self.advance(); q.trace_rev = true; }
683                    }
684                }
685
686                Tok::Kw(k, _) if k == "TRAVERSE" => {
687                    self.advance();
688                    let rel = match self.advance() {
689                        Tok::Ident(s) | Tok::Kw(_, s) => s,
690                        other => bail!("TRAVERSE: expected relation name, got {:?}", other),
691                    };
692                    q.traverse = Some(rel);
693                }
694
695                // Unknown token. This used to be `self.advance()` — a silent
696                // skip that answered a different query than the one asked.
697                other => bail!(
698                    "unexpected {:?} in query. Expected one of: AS OF, VALID AS OF, \
699                     WHERE, SEARCH, ORDER BY, LIMIT, OFFSET, GROUP BY, HAVING, \
700                     COUNT, SUM, AVG, MIN, MAX, TRACE, TRAVERSE",
701                    other
702                ),
703            }
704        }
705
706        Ok(q)
707    }
708}
709
710// ── Executor ──────────────────────────────────────────────────────────────────
711
712/// Resolve a field name against a node, including the `_`-prefixed metadata
713/// fields that live on the node rather than in its data payload.
714fn field_value(node: &Node, field: &str) -> Value {
715    match field {
716        "_id"   => Value::String(node.id.clone()),
717        "_coll" => Value::String(node.coll.clone()),
718        "_hash" => Value::String(node.hash.clone()),
719        "_seq"  => json!(node.seq),
720        _ => node.data.get(field).cloned().unwrap_or(Value::Null),
721    }
722}
723
724fn cmp_op(a: &Value, op: &str, b: &Value) -> bool {
725    // An ORDERING comparison against a null/missing field is never true.
726    //
727    // OrderedValue sorts Null below every number, so `<` and `<=` used to
728    // report that a document with NO `fee` field at all satisfied
729    // `WHERE fee < 5`. `>` and `>=` excluded it — the asymmetry was the tell.
730    //
731    // The Python reference has always excluded it (query.py: `if a is None:
732    // return False`, placed deliberately AFTER the = / != arms), so this was
733    // a live divergence between the two engines as well as a wrong answer:
734    // asking for cheap jobs should not return jobs with no price.
735    //
736    // `=` and `!=` keep operating on null, exactly as Python does, so
737    // `WHERE x != 5` still matches a row where x is absent and `WHERE x = NULL`
738    // still works. `BETWEEN` is built from `>=` and `<=` and so inherits this.
739    //
740    // This also makes the scan path and the sorted-index path agree. A
741    // document whose field is absent is not in that field's index, so an index
742    // range scan could never have returned it — without this fix the two paths
743    // answered the same query differently depending on whether an index
744    // happened to exist.
745    if matches!(op, "<" | "<=" | ">" | ">=") && a.is_null() {
746        return false;
747    }
748    let a = OrderedValue::from(a);
749    let b = OrderedValue::from(b);
750    match op {
751        "="  => a == b,
752        "!=" => a != b,
753        ">"  => a >  b,
754        "<"  => a <  b,
755        ">=" => a >= b,
756        "<=" => a <= b,
757        _    => false,
758    }
759}
760
761/// Render a JSON scalar for text matching. Strings pass through unquoted so a
762/// LIKE pattern is compared against the value a user sees, not against its
763/// JSON encoding (`"abc"` with the quotes included).
764fn as_text(v: &Value) -> String {
765    match v {
766        Value::String(s) => s.clone(),
767        Value::Null => String::new(),
768        other => other.to_string(),
769    }
770}
771
772/// SQL LIKE matching: `%` matches any run of characters (including empty),
773/// `_` matches exactly one. Implemented as an iterative two-pointer scan with
774/// backtracking to the last `%`, which is linear in practice and needs no
775/// regex dependency. Operates on chars, so multi-byte values match correctly.
776fn like_match(value: &str, pattern: &str, ci: bool) -> bool {
777    like_match_esc(value, pattern, ci, None)
778}
779
780/// `LIKE` with an optional escape character.
781///
782/// When `esc` is set, the character following it in the pattern is LITERAL —
783/// so `ESCAPE '/'` makes `/%` mean a real percent sign rather than a wildcard.
784/// That is the whole point of the clause: it lets a caller search for the
785/// wildcards themselves, which is exactly what an introspection query does
786/// when a schema name may contain `_`.
787///
788/// Case folding happens BEFORE escape resolution, which matters: folding the
789/// escape character itself would make `ESCAPE 'A'` and `ESCAPE 'a'` differ
790/// under ILIKE, so the escape char is folded to match.
791fn like_match_esc(value: &str, pattern: &str, ci: bool, esc: Option<char>) -> bool {
792    let (v, p): (Vec<char>, Vec<char>) = if ci {
793        (value.to_lowercase().chars().collect(), pattern.to_lowercase().chars().collect())
794    } else {
795        (value.chars().collect(), pattern.chars().collect())
796    };
797
798    let esc = esc.map(|c| if ci { c.to_lowercase().next().unwrap_or(c) } else { c });
799
800    // Resolve the pattern into (char, is_literal) pairs ONCE, so the matcher
801    // below is unchanged in shape and the escape rule cannot be applied
802    // inconsistently on a backtrack.
803    //
804    // A trailing escape character with nothing after it is treated as a
805    // literal occurrence of itself rather than an error: PostgreSQL rejects
806    // it, but this endpoint's job on a malformed catalogue pattern is to
807    // answer no-rows, not to fail a client's connection.
808    let pat: Vec<(char, bool)> = {
809        let mut out: Vec<(char, bool)> = Vec::with_capacity(p.len());
810        let mut i = 0usize;
811        while i < p.len() {
812            if Some(p[i]) == esc {
813                if i + 1 < p.len() {
814                    out.push((p[i + 1], true));
815                    i += 2;
816                } else {
817                    out.push((p[i], true));
818                    i += 1;
819                }
820            } else {
821                out.push((p[i], false));
822                i += 1;
823            }
824        }
825        out
826    };
827
828    let mut vi = 0usize;
829    let mut pi = 0usize;
830    // Position to resume from if the current `%` expansion turns out too short.
831    let mut star: Option<(usize, usize)> = None;
832
833    while vi < v.len() {
834        let wild_any = pi < pat.len() && pat[pi].0 == '%' && !pat[pi].1;
835        let wild_one = pi < pat.len() && pat[pi].0 == '_' && !pat[pi].1;
836        if pi < pat.len() && (wild_one || pat[pi].0 == v[vi]) {
837            vi += 1;
838            pi += 1;
839        } else if wild_any {
840            star = Some((pi, vi));
841            pi += 1;
842        } else if let Some((sp, sv)) = star {
843            // Backtrack: let the `%` swallow one more character.
844            pi = sp + 1;
845            vi = sv + 1;
846            star = Some((sp, vi));
847        } else {
848            return false;
849        }
850    }
851    // Trailing `%`s can still match the empty remainder — but an ESCAPED `%`
852    // is a real character and must not be skipped here.
853    while pi < pat.len() && pat[pi].0 == '%' && !pat[pi].1 { pi += 1; }
854    pi == pat.len()
855}
856
857// ── POSIX ERE, the subset psql actually writes ──────────────────────────────
858//
859// A hand-rolled backtracking matcher. Still deliberately no `regex` crate: it
860// would add a dependency tree to an engine whose small footprint is a selling
861// point. What changed is the SUBSET. It used to be `^ $ .` and literal text,
862// which was everything `\dn` and `\dt` needed — and then `\d orders` sent
863// `relname ~ '^(orders)$'` and the group was refused by name. A group, an
864// alternation and the three quantifiers are the whole of what psql generates
865// (`\d ord*` becomes `^(ord.*)$`), so that is the whole of what is added.
866//
867// Supported:  literals · `.` · `^` `$` · `|` · `( )` · `[abc]` `[^a-z]` ·
868//             `*` `+` `?` · `\x` as the literal x
869// Refused BY NAME, never approximated: `{n,m}` intervals, `[[:class:]]`
870// POSIX classes, `\1` back-references and `\d \w \s \b` shorthands. The
871// Python reference engine implements the identical grammar with the identical
872// algorithm — two engines accepting different regex languages is a divergence
873// in a FILTER, which silently includes or excludes rows.
874
875#[derive(Debug, Clone, PartialEq)]
876enum ReNode {
877    Char(char),
878    Any,
879    /// `[...]`: single chars and inclusive ranges, optionally negated.
880    Class { items: Vec<(char, char)>, negated: bool },
881    Start,
882    End,
883    Group(Vec<Vec<ReItem>>),
884}
885
886#[derive(Debug, Clone, Copy, PartialEq)]
887enum ReQuant { One, Opt, Star, Plus }
888
889#[derive(Debug, Clone, PartialEq)]
890struct ReItem { node: ReNode, quant: ReQuant }
891
892/// Compile a pattern, or say exactly which construct is outside the subset.
893fn regex_compile(pattern: &str) -> Result<Vec<Vec<ReItem>>, String> {
894    let p: Vec<char> = pattern.chars().collect();
895    let mut pos = 0usize;
896    let alt = regex_parse_alt(&p, &mut pos, 0)?;
897    if pos < p.len() {
898        // Only a stray `)` can stop the top-level parse early.
899        return Err(format!("regex {:?} has an unmatched ')'", pattern));
900    }
901    Ok(alt)
902}
903
904fn regex_parse_alt(p: &[char], pos: &mut usize, depth: usize) -> Result<Vec<Vec<ReItem>>, String> {
905    let mut branches = vec![];
906    loop {
907        let mut seq: Vec<ReItem> = vec![];
908        while *pos < p.len() {
909            let c = p[*pos];
910            if c == '|' || c == ')' {
911                break;
912            }
913            *pos += 1;
914            let node = match c {
915                '.' => ReNode::Any,
916                '^' => ReNode::Start,
917                '$' => ReNode::End,
918                '(' => {
919                    let inner = regex_parse_alt(p, pos, depth + 1)?;
920                    if *pos >= p.len() || p[*pos] != ')' {
921                        return Err("regex has an unmatched '('".to_string());
922                    }
923                    *pos += 1;
924                    ReNode::Group(inner)
925                }
926                '[' => {
927                    let negated = *pos < p.len() && p[*pos] == '^';
928                    if negated {
929                        *pos += 1;
930                    }
931                    let mut items = vec![];
932                    let mut first = true;
933                    loop {
934                        if *pos >= p.len() {
935                            return Err("regex has an unmatched '['".to_string());
936                        }
937                        let ch = p[*pos];
938                        if ch == ']' && !first {
939                            *pos += 1;
940                            break;
941                        }
942                        first = false;
943                        if ch == '[' && p.get(*pos + 1) == Some(&':') {
944                            return Err(
945                                "regex uses a POSIX character class like [[:alpha:]], \
946                                 which this engine does not implement".to_string(),
947                            );
948                        }
949                        let lo = if ch == '\\' {
950                            *pos += 1;
951                            *p.get(*pos).ok_or("regex ends inside an escape")?
952                        } else {
953                            ch
954                        };
955                        *pos += 1;
956                        // `a-z`, but a trailing `-` before `]` is a literal.
957                        if *pos + 1 < p.len() && p[*pos] == '-' && p[*pos + 1] != ']' {
958                            let hi = p[*pos + 1];
959                            *pos += 2;
960                            if hi < lo {
961                                return Err(format!("regex range {}-{} is reversed", lo, hi));
962                            }
963                            items.push((lo, hi));
964                        } else {
965                            items.push((lo, lo));
966                        }
967                    }
968                    ReNode::Class { items, negated }
969                }
970                '{' | '}' => {
971                    return Err(format!(
972                        "regex uses {:?} (an interval like a{{2,3}}), which this engine \
973                         does not implement", c
974                    ))
975                }
976                '*' | '+' | '?' => {
977                    return Err(format!("regex has a {:?} with nothing to repeat", c))
978                }
979                '\\' => {
980                    let e = *p.get(*pos).ok_or("regex ends inside an escape")?;
981                    *pos += 1;
982                    if e.is_ascii_digit() {
983                        return Err("regex uses a back-reference like \\1, which this \
984                                    engine does not implement".to_string());
985                    }
986                    if matches!(e, 'd' | 'D' | 'w' | 'W' | 's' | 'S' | 'b' | 'B') {
987                        return Err(format!(
988                            "regex uses the shorthand class \\{}, which this engine does \
989                             not implement — write the [..] class out", e
990                        ));
991                    }
992                    ReNode::Char(e)
993                }
994                other => ReNode::Char(other),
995            };
996            let quant = match p.get(*pos) {
997                Some('*') => { *pos += 1; ReQuant::Star }
998                Some('+') => { *pos += 1; ReQuant::Plus }
999                Some('?') => { *pos += 1; ReQuant::Opt }
1000                _ => ReQuant::One,
1001            };
1002            if quant != ReQuant::One && matches!(node, ReNode::Start | ReNode::End) {
1003                return Err("regex repeats an anchor, which is meaningless".to_string());
1004            }
1005            seq.push(ReItem { node, quant });
1006        }
1007        branches.push(seq);
1008        if *pos < p.len() && p[*pos] == '|' {
1009            *pos += 1;
1010            continue;
1011        }
1012        if *pos < p.len() && p[*pos] == ')' && depth == 0 {
1013            return Err("regex has an unmatched ')'".to_string());
1014        }
1015        return Ok(branches);
1016    }
1017}
1018
1019fn re_class_hit(items: &[(char, char)], negated: bool, c: char) -> bool {
1020    items.iter().any(|(lo, hi)| *lo <= c && c <= *hi) != negated
1021}
1022
1023/// Match one atom at `pos`, then hand every possible continuation to `k`.
1024fn re_atom(node: &ReNode, t: &[char], pos: usize, k: &dyn Fn(usize) -> bool) -> bool {
1025    match node {
1026        ReNode::Char(c) => pos < t.len() && t[pos] == *c && k(pos + 1),
1027        ReNode::Any => pos < t.len() && k(pos + 1),
1028        ReNode::Class { items, negated } => {
1029            pos < t.len() && re_class_hit(items, *negated, t[pos]) && k(pos + 1)
1030        }
1031        ReNode::Start => pos == 0 && k(pos),
1032        ReNode::End => pos == t.len() && k(pos),
1033        ReNode::Group(alt) => alt.iter().any(|seq| re_seq(seq, t, pos, k)),
1034    }
1035}
1036
1037/// Greedy `*`: take one more, else fall through to the rest.
1038fn re_star(node: &ReNode, rest: &[ReItem], t: &[char], pos: usize, k: &dyn Fn(usize) -> bool) -> bool {
1039    // A repetition that consumed nothing must not recurse, or `()*` loops.
1040    re_atom(node, t, pos, &|p| p != pos && re_star(node, rest, t, p, k)) || re_seq(rest, t, pos, k)
1041}
1042
1043fn re_seq(seq: &[ReItem], t: &[char], pos: usize, k: &dyn Fn(usize) -> bool) -> bool {
1044    let Some(item) = seq.first() else { return k(pos) };
1045    let rest = &seq[1..];
1046    match item.quant {
1047        ReQuant::One => re_atom(&item.node, t, pos, &|p| re_seq(rest, t, p, k)),
1048        ReQuant::Opt => {
1049            re_atom(&item.node, t, pos, &|p| re_seq(rest, t, p, k)) || re_seq(rest, t, pos, k)
1050        }
1051        ReQuant::Star => re_star(&item.node, rest, t, pos, k),
1052        ReQuant::Plus => re_atom(&item.node, t, pos, &|p| re_star(&item.node, rest, t, p, k)),
1053    }
1054}
1055
1056/// Why `pattern` is outside the supported subset, or `None` when it compiles.
1057///
1058/// Refused rather than approximated — see the module comment above. Every
1059/// message names the construct, because "regex error" sends the reader to
1060/// fix the wrong thing.
1061fn regex_error(pattern: &str) -> Option<String> {
1062    regex_compile(pattern).err()
1063}
1064
1065/// POSIX ERE matching over the documented subset. Unanchored patterns search
1066/// for a match anywhere, exactly as `~` does in Postgres.
1067///
1068/// A pattern outside the subset matches NOTHING here; callers validate with
1069/// `regex_error` at parse time so that case is reported, never reached.
1070fn regex_match(value: &str, pattern: &str, ci: bool) -> bool {
1071    let (v, p) = if ci {
1072        (value.to_lowercase(), pattern.to_lowercase())
1073    } else {
1074        (value.to_string(), pattern.to_string())
1075    };
1076    let Ok(alt) = regex_compile(&p) else { return false };
1077    let t: Vec<char> = v.chars().collect();
1078    let done = |_: usize| true;
1079    (0..=t.len()).any(|start| alt.iter().any(|seq| re_seq(seq, &t, start, &done)))
1080}
1081
1082/// Public aliases so the SQL `SELECT` engine matches patterns with EXACTLY
1083/// the same code NQL does.
1084///
1085/// Two implementations of `LIKE` or of the regex subset would be two chances
1086/// for the SQL surface and the NQL surface to disagree about the same
1087/// operator on the same data — and a filter that disagrees with itself is the
1088/// silent-wrong-row class this engine keeps having to remove.
1089pub fn regex_match_pub(value: &str, pattern: &str, ci: bool) -> bool {
1090    regex_match(value, pattern, ci)
1091}
1092
1093/// Why a pattern is outside the supported regex subset, or `None`. See
1094/// `Pred::Regex`.
1095pub fn regex_error_pub(pattern: &str) -> Option<String> {
1096    regex_error(pattern)
1097}
1098
1099/// SQL `LIKE` matching — `%` any run, `_` exactly one char.
1100pub fn like_match_pub(value: &str, pattern: &str, ci: bool) -> bool {
1101    like_match_esc(value, pattern, ci, None)
1102}
1103
1104/// `LIKE ... ESCAPE 'c'` — the escaped form.
1105///
1106/// Added because SQLAlchemy 2.0.53 started emitting it in the catalogue query
1107/// its inspector runs on connect. 2.0.52 did not, so the endpoint went from
1108/// working to refusing with `expected ')', got ESCAPE` on a dependency bump
1109/// nobody here made. An introspection query is the FIRST thing a client sends,
1110/// so refusing it does not degrade one feature — the connection is unusable.
1111pub fn like_match_escape_pub(value: &str, pattern: &str, ci: bool, esc: char) -> bool {
1112    like_match_esc(value, pattern, ci, Some(esc))
1113}
1114
1115/// Evaluate a predicate against anything that can resolve a field name.
1116///
1117/// Generic over the row source so ONE implementation serves both `WHERE`
1118/// (over stored nodes) and `HAVING` (over aggregated rows, which are plain
1119/// JSON objects with no node behind them). Two copies would be two chances for
1120/// the operators to drift apart.
1121fn eval_pred_with(get: &dyn Fn(&str) -> Value, pred: &Pred) -> bool {
1122    match pred {
1123        Pred::Cmp { field, op, value } => cmp_op(&get(field), op, value),
1124
1125        Pred::In { field, values, negated } => {
1126            let fv = get(field);
1127            let hit = values.iter().any(|v| cmp_op(&fv, "=", v));
1128            hit != *negated
1129        }
1130
1131        Pred::Between { field, low, high, negated } => {
1132            let fv = get(field);
1133            // Inclusive on both ends, as in SQL.
1134            let hit = cmp_op(&fv, ">=", low) && cmp_op(&fv, "<=", high);
1135            hit != *negated
1136        }
1137
1138        Pred::Like { field, pattern, negated, ci } => {
1139            let fv = get(field);
1140            // A missing/null field matches no pattern, and NOT LIKE on a null
1141            // field stays false — mirroring SQL's three-valued logic, where a
1142            // predicate over NULL is never true in either polarity.
1143            if fv.is_null() { return false; }
1144            let hit = like_match(&as_text(&fv), pattern, *ci);
1145            hit != *negated
1146        }
1147
1148        Pred::Regex { field, pattern, negated, ci } => {
1149            let fv = get(field);
1150            // Same three-valued logic as LIKE: a predicate over NULL is never
1151            // true in EITHER polarity, so `x !~ 'p'` does not match a row
1152            // where x is absent. Postgres agrees, and psql's catalogue filters
1153            // depend on it.
1154            if fv.is_null() { return false; }
1155            let hit = regex_match(&as_text(&fv), pattern, *ci);
1156            hit != *negated
1157        }
1158
1159        Pred::IsNull { field, negated } => {
1160            // Absent and explicitly-null are both NULL here: a document store
1161            // has no schema, so "the field was never written" and "the field
1162            // holds null" are the same observable state.
1163            get(field).is_null() != *negated
1164        }
1165
1166        Pred::And(terms) => terms.iter().all(|t| eval_pred_with(get, t)),
1167        Pred::Or(terms)  => terms.iter().any(|t| eval_pred_with(get, t)),
1168        Pred::Not(inner) => !eval_pred_with(get, inner),
1169    }
1170}
1171
1172fn eval_pred(node: &Node, pred: &Pred) -> bool {
1173    eval_pred_with(&|f| field_value(node, f), pred)
1174}
1175
1176/// `HAVING` evaluation, over an aggregated row.
1177fn eval_pred_json(obj: &Value, pred: &Pred) -> bool {
1178    eval_pred_with(&|f| obj.get(f).cloned().unwrap_or(Value::Null), pred)
1179}
1180
1181/// Sort by a list of keys, each with its own direction. Earlier keys dominate;
1182/// later ones break ties.
1183fn sort_by_keys<T>(rows: &mut [T], keys: &[OrderKey], get: impl Fn(&T, &str) -> Value) {
1184    rows.sort_by(|a, b| {
1185        for k in keys {
1186            let av = OrderedValue::from(&get(a, &k.field));
1187            let bv = OrderedValue::from(&get(b, &k.field));
1188            let ord = if k.desc { bv.cmp(&av) } else { av.cmp(&bv) };
1189            if ord != std::cmp::Ordering::Equal {
1190                return ord;
1191            }
1192        }
1193        std::cmp::Ordering::Equal
1194    });
1195}
1196
1197/// Apply OFFSET then LIMIT, in that order.
1198///
1199/// SQL semantics: OFFSET skips rows of the RESULT, LIMIT caps what remains.
1200/// An offset past the end yields an empty page rather than an error.
1201fn paginate<T>(rows: Vec<T>, offset: Option<usize>, limit: Option<usize>) -> Vec<T> {
1202    let mut it = rows;
1203    if let Some(off) = offset {
1204        if off >= it.len() {
1205            return vec![];
1206        }
1207        it.drain(..off);
1208    }
1209    if let Some(n) = limit {
1210        it.truncate(n);
1211    }
1212    it
1213}
1214
1215/// Collapse rows into aggregate rows.
1216///
1217/// With `group_field: Some(f)` this yields one row per distinct value of `f`;
1218/// with `None` it yields exactly one row aggregating the whole result set.
1219///
1220/// `count` is the group size, while the aggregate considers ONLY rows whose
1221/// target field is numeric. That split matters and matches the Python
1222/// reference, which computes `count` from the group and the aggregate from
1223/// `[d[af] for d in gdocs if isinstance(d[af], (int, float))]`: a group of 5
1224/// rows where 2 carry a numeric `price` reports `count: 5` and averages over
1225/// 2. Folding non-numeric values in as 1.0 — the behaviour before 3.3.0 —
1226/// silently corrupted every SUM and AVG.
1227fn aggregate_rows(rows: &[Node], spec: &Aggregate) -> Vec<Value> {
1228    // `ints` tracks whether EVERY contributing value was an integer.
1229    //
1230    // Aggregating exclusively in f64 was both a type divergence from the
1231    // Python reference (which returns `66`, not `66.0`, for a sum of integers)
1232    // and a precision bug: f64 cannot represent integers above 2^53 exactly,
1233    // so a SUM over satoshi amounts or block heights silently rounded. SUM /
1234    // MIN / MAX now stay in i64 when the inputs are integral. AVG is always
1235    // fractional — Python's `sum(nums) / len(nums)` is true division — so it
1236    // stays f64 in both engines.
1237    struct Group { count: usize, nums: Vec<f64>, ints: Vec<i64>, all_int: bool }
1238
1239    // First-seen order, so results are stable run to run. HashMap iteration
1240    // order previously made the grouped output nondeterministic.
1241    let mut order: Vec<String> = vec![];
1242    let mut groups: HashMap<String, Group> = HashMap::new();
1243
1244    // The ungrouped case is one group under a fixed key, so a single code path
1245    // serves both and they cannot disagree about the aggregate itself.
1246    const WHOLE: &str = "";
1247
1248    for node in rows {
1249        // Resolved through `field_value`, not `node.data`, so the `_`-prefixed
1250        // metadata fields work here too. Reading the payload directly made
1251        // `SELECT MAX(_seq)` return NULL — with a 200 and a plausible-looking
1252        // single-row answer — even though `SELECT _seq` listed the values and
1253        // `WHERE _seq > 5` filtered on them. "What is the newest sequence?" is
1254        // the question replication and time travel are built on, so a silent
1255        // null there was the worst shape of wrong.
1256        let key = match spec.group_field {
1257            None => WHOLE.to_string(),
1258            Some(ref gf) => match field_value(node, gf) {
1259                Value::Null => "null".to_string(),
1260                v => as_text(&v),
1261            },
1262        };
1263        let entry = groups.entry(key.clone()).or_insert_with(|| {
1264            order.push(key.clone());
1265            Group { count: 0, nums: vec![], ints: vec![], all_int: true }
1266        });
1267        entry.count += 1;
1268        if let Some(ref af) = spec.agg_field {
1269            // A JSON bool is not a number here, matching Python's
1270            // `isinstance(x, (int, float)) and not isinstance(x, bool)`.
1271            if let Value::Number(n) = field_value(node, af) {
1272                if let Some(i) = n.as_i64() {
1273                    entry.ints.push(i);
1274                    entry.nums.push(i as f64);
1275                } else if let Some(f) = n.as_f64() {
1276                    entry.all_int = false;
1277                    entry.nums.push(f);
1278                }
1279            }
1280        }
1281    }
1282
1283    // An ungrouped aggregate over ZERO rows still returns one row — COUNT of
1284    // an empty set is 0, not "no answer". A grouped aggregate over zero rows
1285    // correctly returns no groups.
1286    if spec.group_field.is_none() && order.is_empty() {
1287        order.push(WHOLE.to_string());
1288        groups.insert(WHOLE.to_string(),
1289                      Group { count: 0, nums: vec![], ints: vec![], all_int: true });
1290    }
1291
1292    order.into_iter().map(|k| {
1293        let g = &groups[&k];
1294        let mut obj = serde_json::Map::new();
1295        if let Some(ref gf) = spec.group_field {
1296            obj.insert(gf.clone(), Value::String(k.clone()));
1297        }
1298        obj.insert("count".to_string(), json!(g.count));
1299
1300        // Empty aggregate input yields null, not 0 and not +/-infinity — the
1301        // old fold seeded MIN with f64::INFINITY, which serialises to null
1302        // anyway but would report INFINITY through any non-JSON path.
1303        let int_path = g.all_int && !g.ints.is_empty();
1304        let agg_val: Value = match spec.agg {
1305            GroupAgg::Count => json!(g.count),
1306            _ if g.nums.is_empty() => Value::Null,
1307            // checked_add: an i64 overflow falls back to f64 rather than
1308            // panicking in release or wrapping to a negative sum.
1309            GroupAgg::Sum if int_path => {
1310                match g.ints.iter().try_fold(0i64, |a, &b| a.checked_add(b)) {
1311                    Some(t) => json!(t),
1312                    None => json!(g.nums.iter().sum::<f64>()),
1313                }
1314            }
1315            GroupAgg::Min if int_path => json!(g.ints.iter().min().copied().unwrap()),
1316            GroupAgg::Max if int_path => json!(g.ints.iter().max().copied().unwrap()),
1317            GroupAgg::Sum => json!(g.nums.iter().sum::<f64>()),
1318            // AVG is true division in both engines, so always fractional.
1319            GroupAgg::Avg => json!(g.nums.iter().sum::<f64>() / g.nums.len() as f64),
1320            GroupAgg::Min => json!(g.nums.iter().cloned().fold(f64::INFINITY, f64::min)),
1321            GroupAgg::Max => json!(g.nums.iter().cloned().fold(f64::NEG_INFINITY, f64::max)),
1322        };
1323
1324        // Python-parity key: sum_price / avg_score / min_price / max_price.
1325        if let Some(ref af) = spec.agg_field {
1326            obj.insert(format!("{}_{}", spec.agg.name(), af), agg_val.clone());
1327        }
1328        // `value` is retained as an alias. It was this engine's only aggregate
1329        // key before 3.3.0, so Studio and any existing caller still read it;
1330        // dropping it would be a silent breakage on a client we do not
1331        // control from here.
1332        obj.insert("value".to_string(), agg_val);
1333        Value::Object(obj)
1334    }).collect()
1335}
1336
1337/// Find an `_id = "..."` equality usable as an O(1) index lookup.
1338///
1339/// Only descends through AND nodes. An equality sitting under an OR does not
1340/// constrain the result set — `WHERE _id = "a" OR height > 3` must still return
1341/// the height matches — so treating it as a point lookup would silently drop
1342/// rows. That is precisely the bug the pre-existing `where_order_limit` test
1343/// guards against in the ORDER BY path, one level up.
1344/// What an indexed field can be narrowed to, derived from the predicate.
1345#[derive(Debug, Clone)]
1346enum IndexPlan {
1347    /// A bounded (or half-bounded) range walk over the sorted index.
1348    Range {
1349        field: String,
1350        low: Option<Value>,
1351        high: Option<Value>,
1352        low_incl: bool,
1353        high_incl: bool,
1354    },
1355    /// A set of point lookups — `=` or `IN (...)`.
1356    Values { field: String, values: Vec<Value> },
1357}
1358
1359impl IndexPlan {
1360    fn field(&self) -> &str {
1361        match self {
1362            IndexPlan::Range { field, .. } => field,
1363            IndexPlan::Values { field, .. } => field,
1364        }
1365    }
1366}
1367
1368/// Collect every constraint an AND-reachable conjunct places on a field.
1369///
1370/// SAFETY PROPERTY that makes this whole path sound: the returned plan only
1371/// ever needs to describe a SUPERSET of the matching rows. The full predicate
1372/// is re-evaluated on whatever candidates come back, so an imprecise plan
1373/// costs time, never correctness. That is why it is fine to ignore constraints
1374/// this planner does not understand.
1375///
1376/// Only descends through `And`. A constraint under an `Or` does not restrict
1377/// the result set — `WHERE fee > 100 OR status = "open"` must still return the
1378/// status matches — so narrowing on one arm would silently drop rows. `Not` is
1379/// likewise never entered: a negated range is not a range.
1380fn collect_index_constraints(pred: &Pred, out: &mut Vec<IndexPlan>) {
1381    match pred {
1382        Pred::And(terms) => {
1383            for t in terms {
1384                collect_index_constraints(t, out);
1385            }
1386        }
1387
1388        Pred::Cmp { field, op, value } => {
1389            // `_id` has its own O(1) path and is not in the sorted index.
1390            if field == "_id" {
1391                return;
1392            }
1393            match op.as_str() {
1394                "=" => out.push(IndexPlan::Values {
1395                    field: field.clone(),
1396                    values: vec![value.clone()],
1397                }),
1398                ">" | ">=" => out.push(IndexPlan::Range {
1399                    field: field.clone(),
1400                    low: Some(value.clone()),
1401                    high: None,
1402                    low_incl: op == ">=",
1403                    high_incl: true,
1404                }),
1405                "<" | "<=" => out.push(IndexPlan::Range {
1406                    field: field.clone(),
1407                    low: None,
1408                    high: Some(value.clone()),
1409                    low_incl: true,
1410                    high_incl: op == "<=",
1411                }),
1412                // `!=` matches almost everything; a range walk would be
1413                // slower than the scan it replaces.
1414                _ => {}
1415            }
1416        }
1417
1418        Pred::Between { field, low, high, negated: false } => {
1419            out.push(IndexPlan::Range {
1420                field: field.clone(),
1421                low: Some(low.clone()),
1422                high: Some(high.clone()),
1423                low_incl: true,   // SQL BETWEEN is inclusive on both ends
1424                high_incl: true,
1425            });
1426        }
1427
1428        Pred::In { field, values, negated: false } => {
1429            out.push(IndexPlan::Values {
1430                field: field.clone(),
1431                values: values.clone(),
1432            });
1433        }
1434
1435        // NOT IN / NOT BETWEEN / LIKE / IS NULL cannot be served by a range
1436        // walk: they either match the complement of a range, or they are not
1437        // an ordering predicate at all. IS NULL specifically can NEVER use
1438        // this index — a document whose field is absent is not in the index,
1439        // so an index scan would return the exact opposite of the answer.
1440        _ => {}
1441    }
1442}
1443
1444/// Merge same-field constraints and choose the most selective indexed plan.
1445///
1446/// `fee > 10 AND fee < 100` becomes ONE bounded walk rather than a half-open
1447/// one, and when several fields are indexed the planner asks the index how
1448/// many rows each range covers and takes the narrowest — rather than
1449/// committing to whichever field it happened to see first.
1450fn choose_index_plan(db: &Db, coll: &str, pred: &Pred) -> Option<IndexPlan> {
1451    let mut raw = vec![];
1452    collect_index_constraints(pred, &mut raw);
1453    raw.retain(|p| db.has_sorted_index(coll, p.field()));
1454    if raw.is_empty() {
1455        return None;
1456    }
1457
1458    // Merge per field.
1459    let mut merged: Vec<IndexPlan> = vec![];
1460    for plan in raw {
1461        let field = plan.field().to_string();
1462        let existing = merged.iter().position(|m| m.field() == field);
1463        match (existing, plan) {
1464            (None, p) => merged.push(p),
1465
1466            // Two ranges on the same field: intersect the bounds.
1467            (Some(i), IndexPlan::Range { low, high, low_incl, high_incl, .. }) => {
1468                if let IndexPlan::Range {
1469                    low: ref mut elow, high: ref mut ehigh,
1470                    low_incl: ref mut eli, high_incl: ref mut ehi, ..
1471                } = merged[i] {
1472                    if let Some(l) = low {
1473                        let tighter = match elow {
1474                            None => true,
1475                            Some(cur) => OrderedValue::from(&l) > OrderedValue::from(&*cur),
1476                        };
1477                        if tighter { *elow = Some(l); *eli = low_incl; }
1478                    }
1479                    if let Some(h) = high {
1480                        let tighter = match ehigh {
1481                            None => true,
1482                            Some(cur) => OrderedValue::from(&h) < OrderedValue::from(&*cur),
1483                        };
1484                        if tighter { *ehigh = Some(h); *ehi = high_incl; }
1485                    }
1486                }
1487                // A Range arriving where a Values plan already sits is
1488                // ignored: the point lookups are already at least as
1489                // selective, and the predicate re-runs regardless.
1490            }
1491
1492            // An equality/IN beats a range on the same field.
1493            (Some(i), p @ IndexPlan::Values { .. }) => {
1494                if matches!(merged[i], IndexPlan::Range { .. }) {
1495                    merged[i] = p;
1496                }
1497            }
1498        }
1499    }
1500
1501    // Pick the narrowest, measured against the index rather than guessed.
1502    // A Values plan costs one point lookup per arm, so its cardinality is
1503    // the sum of those buckets.
1504    let mut best: Option<(usize, IndexPlan)> = None;
1505    for plan in merged {
1506        let card = match &plan {
1507            IndexPlan::Range { field, low, high, low_incl, high_incl } => db
1508                .range_cardinality(coll, field, low.as_ref(), high.as_ref(),
1509                                   *low_incl, *high_incl)
1510                .unwrap_or(usize::MAX),
1511            IndexPlan::Values { field, values } => values
1512                .iter()
1513                .map(|v| db.range_cardinality(coll, field, Some(v), Some(v), true, true)
1514                          .unwrap_or(usize::MAX))
1515                .fold(0usize, |a, b| a.saturating_add(b)),
1516        };
1517        if best.as_ref().map(|(c, _)| card < *c).unwrap_or(true) {
1518            best = Some((card, plan));
1519        }
1520    }
1521    best.map(|(_, p)| p)
1522}
1523
1524fn id_point_lookup(pred: &Pred) -> Option<String> {
1525    match pred {
1526        Pred::Cmp { field, op, value } if field == "_id" && op == "=" => {
1527            if let Value::String(s) = value { Some(s.clone()) } else { None }
1528        }
1529        Pred::And(terms) => terms.iter().find_map(id_point_lookup),
1530        _ => None,
1531    }
1532}
1533
1534// `matches_valid_as_of` and `node_contains_text` MOVED to `crate::relation`,
1535// which is now the single definition of what these two verbs mean. They are
1536// re-exported here rather than reimplemented: the SQL evaluator reads
1537// relations through `relation::read`, and a second copy of "is this row valid
1538// at this date" living in the query language is precisely the duplication that
1539// folding NQL into neSQL exists to remove.
1540use crate::relation::{matches_valid_as_of, node_contains_text};
1541
1542/// A node as a flat query row: data fields at the top level plus the `_`-prefixed
1543/// metadata. Public so the HTTP single-row GET returns the SAME shape a query row
1544/// has — one definition, so the two surfaces cannot drift apart.
1545pub fn node_to_json(node: &Node) -> Value {
1546    let mut obj = if let Value::Object(m) = &node.data {
1547        m.clone()
1548    } else {
1549        serde_json::Map::new()
1550    };
1551    obj.insert("_id".to_string(),   Value::String(node.id.clone()));
1552    obj.insert("_hash".to_string(), Value::String(node.hash.clone()));
1553    obj.insert("_seq".to_string(),  json!(node.seq));
1554    obj.insert("_coll".to_string(), Value::String(node.coll.clone()));
1555    if let Some(ref vf) = node.valid_from {
1556        obj.insert("_valid_from".to_string(), Value::String(vf.clone()));
1557    }
1558    if let Some(ref vt) = node.valid_to {
1559        obj.insert("_valid_to".to_string(), Value::String(vt.clone()));
1560    }
1561    if !node.caused_by.is_empty() {
1562        obj.insert("_caused_by".to_string(), Value::Array(
1563            node.caused_by.iter().map(|h| Value::String(h.clone())).collect()
1564        ));
1565    }
1566    Value::Object(obj)
1567}
1568
1569/// Execute a NQL query against the DAG database.
1570/// Parse NQL into a `Query` WITHOUT touching the database.
1571///
1572/// `execute` already does exactly this as its first step; exposing it separately
1573/// lets callers validate a query before deciding to run it. The natural-language
1574/// planner (`/v1/databases/:name/cast`) uses it to answer "is this runnable?"
1575/// without side effects — checking the text against the real grammar rather than
1576/// pattern-matching it, because the parser is the only authority on that.
1577pub fn parse(nql: &str) -> Result<Query> {
1578    let mut lexer = Lexer::new(nql);
1579    let toks = lexer.tokenize();
1580    let mut parser = Parser::new(toks);
1581    parser.parse()
1582}
1583
1584pub fn execute(db: &Db, nql: &str) -> Result<Vec<Value>> {
1585    // One parse path, shared with the public `parse()` above — so validation and
1586    // execution can never disagree about what is well-formed.
1587    let q = parse(nql)?;
1588
1589    // ── Candidate generation ──────────────────────────────────────────────────
1590
1591    // Fast path: single equality filter on _id with no AS OF.
1592    // Skip the O(n) collection scan — go straight to the id index (O(1) file read).
1593    // This turns `FROM coll WHERE _id = "x" LIMIT 1` from a full-table-scan into
1594    // a single file read, giving orders-of-magnitude speedup for point lookups.
1595    let id_eq_fast_path: Option<String> = if q.as_of.is_none() && q.trace.is_none() {
1596        q.where_.as_ref().and_then(id_point_lookup)
1597    } else { None };
1598
1599    let candidates: Vec<Node> = if let Some(ref target_id) = id_eq_fast_path {
1600        // O(1) direct id-index lookup — skip full collection scan entirely
1601        db.get(&q.coll, target_id).into_iter().collect()
1602    } else if let Some(seq_target) = q.as_of {
1603        // AS OF: return each doc's version at or before target seq.
1604        //
1605        // Over the live ids PLUS the deleted ones. Walking only `id_index`
1606        // meant a DELETED document was invisible at every sequence, including
1607        // sequences before the delete where it demonstrably existed — so
1608        // `AS OF` contradicted the promise that a delete is a tombstone rather
1609        // than an erasure. `get_as_of` reaches the chain through the graveyard
1610        // pointer, and returns nothing for a sequence at or after the
1611        // tombstone, where the document really is gone.
1612        db.list_ids_including_deleted(&q.coll).into_iter()
1613            .filter_map(|id| db.get_as_of(&q.coll, &id, seq_target))
1614            .collect()
1615    } else if let Some(plan) = q.where_.as_ref()
1616        // An indexed range or point-set scan, when a sorted index covers a
1617        // field the predicate constrains.
1618        //
1619        // Deliberately NOT attempted for AS OF: the sorted index holds current
1620        // versions only (a superseded hash is dropped on overwrite), so an
1621        // index scan would answer a historical query with present-day rows.
1622        // AS OF is handled by the branch above, which walks the id index and
1623        // resolves each document at the target seq.
1624        .filter(|_| q.as_of.is_none())
1625        .and_then(|p| choose_index_plan(db, &q.coll, p))
1626    {
1627        // The full predicate re-runs on these candidates below, so the plan
1628        // only has to be a superset — it can never make the answer wrong.
1629        let got = match &plan {
1630            IndexPlan::Range { field, low, high, low_incl, high_incl } => db.range_scan(
1631                &q.coll, field, low.as_ref(), high.as_ref(), *low_incl, *high_incl),
1632            IndexPlan::Values { field, values } => db.index_lookup(&q.coll, field, values),
1633        };
1634        match got {
1635            Some(nodes) => nodes,
1636            // The index vanished between planning and execution. Fall back
1637            // rather than answering from nothing.
1638            None => db.list(&q.coll),
1639        }
1640    } else if q.order_by.len() == 1 && q.aggregate.is_none() {
1641        // ORDER BY with optional sorted index — get candidates in order.
1642        //
1643        // Single key only: the sorted index is per-field, so a multi-key sort
1644        // cannot be served from it and falls through to the post-filter sort
1645        // below. Never used when aggregating either, because the sort then
1646        // applies to the GROUPED rows, which do not exist yet.
1647        //
1648        // Push LIMIT down into the index scan ONLY when nothing filters rows
1649        // after candidate generation. WHERE / SEARCH / VALID AS OF all run on
1650        // the candidate set below, so truncating to the top-k FIRST returns
1651        // incomplete results: `WHERE n_tx > 100 ORDER BY height LIMIT 10`
1652        // would fetch the 10 lowest blocks by height and then filter — losing
1653        // matches past the top-k window. The Python reference filters → sorts
1654        // → limits (engine.py execute()); this keeps the engines in agreement.
1655        let key = &q.order_by[0];
1656        let has_post_filters = q.where_.is_some()
1657            || q.search.is_some()
1658            || q.valid_as_of.is_some();
1659        let limit = if has_post_filters {
1660            9_999_999
1661        } else {
1662            // OFFSET is applied AFTER the sort, so the pushdown has to fetch
1663            // offset + limit rows and discard the prefix later. Fetching only
1664            // `limit` would return the first page for every page.
1665            match q.limit {
1666                Some(n) => n.saturating_add(q.offset.unwrap_or(0)),
1667                None => 9_999_999,
1668            }
1669        };
1670        if key.desc {
1671            db.order_by_desc(&q.coll, &key.field, limit)
1672        } else {
1673            db.order_by_asc(&q.coll, &key.field, limit)
1674        }
1675    } else if let (Some(n), true) = (q.limit, q.where_.is_none()
1676            && q.search.is_none() && q.trace.is_none()
1677            && q.traverse.is_none() && q.aggregate.is_none()
1678            && q.order_by.is_empty() && q.offset.is_none()
1679            && q.valid_as_of.is_none()) {
1680        // LIMIT-only fast path: no filters, no ordering, no trace.
1681        // Take only the first N IDs from the id-index and fetch those docs.
1682        // This makes `FROM coll LIMIT 1` O(N) not O(total) — critical for
1683        // the Studio "Preparing…" phase which samples every collection.
1684        db.id_index
1685            .list_ids(&q.coll)
1686            .into_iter()
1687            .take(n)
1688            .filter_map(|id| db.get(&q.coll, &id))
1689            .collect()
1690    } else {
1691        // Default: all docs in collection
1692        db.list(&q.coll)
1693    };
1694
1695    // ── WHERE filter ──────────────────────────────────────────────────────────
1696
1697    let mut rows: Vec<Node> = candidates.into_iter()
1698        .filter(|n| q.where_.as_ref().map(|p| eval_pred(n, p)).unwrap_or(true))
1699        .filter(|n| q.valid_as_of.as_deref()
1700                       .map(|d| matches_valid_as_of(n, d))
1701                       .unwrap_or(true))
1702        .filter(|n| q.search.as_deref()
1703                       .map(|t| node_contains_text(n, t))
1704                       .unwrap_or(true))
1705        .collect();
1706
1707    // ── TRACE ─────────────────────────────────────────────────────────────────
1708
1709    if let Some(ref _edge_type) = q.trace {
1710        let limit = q.limit.unwrap_or(1000);
1711        let mut traced: Vec<Node> = vec![];
1712        for root in &rows {
1713            let chain = db.trace(&root.hash, q.trace_rev, limit);
1714            traced.extend(chain);
1715        }
1716        rows = traced;
1717    }
1718
1719    // ── TRAVERSE rel — one-hop named-relation lookup ──────────────────────────
1720
1721    if let Some(ref rel) = q.traverse {
1722        let mut traversed: Vec<Node> = vec![];
1723        for root in &rows {
1724            let frm = format!("{}:{}", root.coll, root.id);
1725            let neighbors = db.neighbors(&frm, rel);
1726            traversed.extend(neighbors);
1727        }
1728        rows = traversed;
1729    }
1730
1731    // ── Aggregate → HAVING → ORDER BY → OFFSET → LIMIT ───────────────────────
1732    //
1733    // This is the SQL pipeline order, and getting it wrong was a live source
1734    // of silently-wrong answers. The old order was ORDER BY → LIMIT → GROUP BY,
1735    // which means:
1736    //
1737    //   `LIMIT 5 GROUP BY status COUNT` truncated the INPUT to five rows and
1738    //   then grouped them, so with twelve rows across three statuses the
1739    //   counts summed to 5 instead of 12. A confident wrong aggregate.
1740    //
1741    //   `ORDER BY count DESC GROUP BY status COUNT` sorted the raw documents
1742    //   on a field none of them carry (`count` only exists after grouping),
1743    //   so the grouped output came back in arbitrary order and the clause was
1744    //   silently inert.
1745    //
1746    // In SQL, LIMIT and ORDER BY apply to the RESULT. They now do here.
1747
1748    if let Some(ref spec) = q.aggregate {
1749        let mut out = aggregate_rows(&rows, spec);
1750
1751        // HAVING filters the aggregated rows, so it can test `count`,
1752        // `sum_fee` or the group key — none of which exist before this point.
1753        if let Some(ref pred) = q.having {
1754            out.retain(|row| eval_pred_json(row, pred));
1755        }
1756
1757        if !q.order_by.is_empty() {
1758            sort_by_keys(&mut out, &q.order_by,
1759                         |row, f| row.get(f).cloned().unwrap_or(Value::Null));
1760        } else if let Some(ref gf) = spec.group_field {
1761            // Deterministic default: groups sorted by key.
1762            //
1763            // NOT first-seen order. The Python reference draws candidates from
1764            // a `set`, so its input row order is arbitrary; a first-seen
1765            // ordering would differ between the two engines even though both
1766            // are internally consistent. Sorting by the key gives one answer
1767            // they can agree on, which the cross-engine parity suite pins.
1768            let gf = gf.clone();
1769            out.sort_by(|a, b| {
1770                as_text(&a.get(&gf).cloned().unwrap_or(Value::Null))
1771                    .cmp(&as_text(&b.get(&gf).cloned().unwrap_or(Value::Null)))
1772            });
1773        }
1774
1775        return Ok(paginate(out, q.offset, q.limit));
1776    }
1777
1778    if q.having.is_some() {
1779        bail!("HAVING requires an aggregate — add GROUP BY <field>, or use WHERE \
1780               to filter individual rows");
1781    }
1782
1783    // ── ORDER BY (post-filter sort if no sorted index was used) ──────────────
1784
1785    if !q.order_by.is_empty() {
1786        // The single-key sorted-index path above already returned candidates
1787        // in order, but only when nothing filtered them afterwards. Re-sort
1788        // whenever a filter ran, or whenever the sort has more than one key.
1789        let index_path_held = q.order_by.len() == 1
1790            && q.as_of.is_none()
1791            && q.where_.is_none()
1792            && q.search.is_none()
1793            && q.valid_as_of.is_none()
1794            && q.trace.is_none()
1795            && q.traverse.is_none();
1796        if !index_path_held {
1797            sort_by_keys(&mut rows, &q.order_by,
1798                         |n, f| field_value(n, f));
1799        }
1800    }
1801
1802    // ── OFFSET then LIMIT ────────────────────────────────────────────────────
1803
1804    let rows = paginate(rows, q.offset, q.limit);
1805
1806    // ── Serialize ─────────────────────────────────────────────────────────────
1807
1808    Ok(rows.into_iter().map(|n| node_to_json(&n)).collect())
1809}
1810
1811/// Parse and execute NQL, returning (rows, count).
1812pub fn query(db: &Db, nql: &str) -> Result<(Vec<Value>, usize)> {
1813    let rows = execute(db, nql)?;
1814    let count = rows.len();
1815    Ok((rows, count))
1816}
1817
1818/// Run a query's WHERE / ORDER BY / OFFSET / LIMIT against rows ALREADY IN
1819/// HAND, rather than against stored documents.
1820///
1821/// This is what makes `pg_catalog` and `information_schema` real queryable
1822/// tables instead of pattern-matched query strings. A catalogue row is
1823/// synthesised from the live database, never stored — but `psql` filters and
1824/// orders it with ordinary SQL, so it needs the ordinary predicate surface.
1825///
1826/// The alternative was to recognise psql's exact query text and answer it from
1827/// a fixed table. That breaks SILENTLY the moment psql changes its query, and
1828/// an empty table list is indistinguishable from "this database has no
1829/// tables" — the same class of confidently-wrong answer as everything else
1830/// this engine has had to fix. So the predicate engine is REUSED here rather
1831/// than a second, poorer copy being written: one `eval_pred_with`, one
1832/// `sort_by_keys`, one `paginate`, already tested.
1833///
1834/// Clauses that only mean something against the log — `AS OF`, `VALID AS OF`,
1835/// `TRACE`, `TRAVERSE`, `SEARCH`, and aggregates — are REFUSED by name. A
1836/// catalogue has no history and no causal edges; silently ignoring the clause
1837/// would answer a time-travel question with present-day rows.
1838pub fn query_rows(rows: Vec<Value>, nql: &str) -> Result<Vec<Value>> {
1839    let q = parse(nql)?;
1840
1841    for (unsupported, clause) in [
1842        (q.as_of.is_some(), "AS OF"),
1843        (q.valid_as_of.is_some(), "VALID AS OF"),
1844        (q.trace.is_some(), "TRACE"),
1845        (q.traverse.is_some(), "TRAVERSE"),
1846        (q.search.is_some(), "SEARCH"),
1847        (q.aggregate.is_some(), "an aggregate"),
1848        (q.having.is_some(), "HAVING"),
1849    ] {
1850        if unsupported {
1851            bail!("{} is not supported on the catalogue table {:?} — a catalogue \
1852                   is synthesised from the current database, so it has no history, \
1853                   no causal edges and nothing to aggregate. Query the collection \
1854                   itself for those", clause, q.coll);
1855        }
1856    }
1857
1858    let get = |row: &Value, field: &str| -> Value {
1859        row.get(field).cloned().unwrap_or(Value::Null)
1860    };
1861
1862    let mut kept: Vec<Value> = match &q.where_ {
1863        None => rows,
1864        Some(pred) => rows
1865            .into_iter()
1866            .filter(|r| eval_pred_with(&|f| get(r, f), pred))
1867            .collect(),
1868    };
1869
1870    if !q.order_by.is_empty() {
1871        sort_by_keys(&mut kept, &q.order_by, get);
1872    }
1873    Ok(paginate(kept, q.offset, q.limit))
1874}
1875
1876#[cfg(test)]
1877mod tests {
1878    use super::*;
1879    use tempfile::tempdir;
1880    use crate::db::Db;
1881
1882    // Returns (TempDir, Db) — the TempDir guard MUST be kept alive by the caller
1883    // (`let (_tmp, db) = setup();`). If it dropped here, its Drop would delete the
1884    // database directory out from under the live Db, and every objects.read()
1885    // (loose object files live on disk) would fail → queries return 0 rows.
1886    fn setup() -> (tempfile::TempDir, Db) {
1887        let dir = tempdir().unwrap();
1888        let db = Db::open(dir.path(), None).unwrap();
1889        db.create_sorted_index("blocks", "height");
1890        for h in 1u64..=5 {
1891            db.put("blocks", &h.to_string(),
1892                serde_json::json!({"height": h, "hash": format!("000{}", h), "n_tx": h * 2}),
1893                vec![], None, None).unwrap();
1894        }
1895        (dir, db)
1896    }
1897
1898    #[test]
1899    fn from_all() {
1900        let (_tmp, db) = setup();
1901        let (rows, count) = query(&db, "FROM blocks").unwrap();
1902        assert_eq!(count, 5);
1903        let _ = rows;
1904    }
1905
1906    #[test]
1907    fn where_eq() {
1908        let (_tmp, db) = setup();
1909        let (rows, count) = query(&db, r#"FROM blocks WHERE _id = "3""#).unwrap();
1910        assert_eq!(count, 1);
1911        assert_eq!(rows[0]["_id"], "3");
1912    }
1913
1914    #[test]
1915    fn order_by_limit() {
1916        let (_tmp, db) = setup();
1917        let (rows, count) = query(&db, "FROM blocks ORDER BY height ASC LIMIT 3").unwrap();
1918        assert_eq!(count, 3);
1919        assert_eq!(rows[0]["height"], 1);
1920        assert_eq!(rows[2]["height"], 3);
1921    }
1922
1923    #[test]
1924    fn order_by_desc() {
1925        let (_tmp, db) = setup();
1926        let (rows, _) = query(&db, "FROM blocks ORDER BY height DESC LIMIT 2").unwrap();
1927        assert_eq!(rows[0]["height"], 5);
1928    }
1929
1930    #[test]
1931    fn where_gt() {
1932        let (_tmp, db) = setup();
1933        let (rows, _) = query(&db, "FROM blocks WHERE height > 3").unwrap();
1934        assert_eq!(rows.len(), 2);
1935    }
1936
1937    /// Regression: WHERE + ORDER BY + LIMIT must not truncate candidates
1938    /// before the filter runs. setup() gives heights 1..=5 with n_tx = h*2;
1939    /// the predicate matches ONLY the two highest heights (4, 5). The old
1940    /// code passed LIMIT into the sorted-index top-k first: it fetched
1941    /// heights [1, 2], filtered on n_tx >= 8, and returned ZERO rows even
1942    /// though two matches exist. Python reference returns [4, 5].
1943    #[test]
1944    fn where_order_limit_does_not_truncate_before_filter() {
1945        let (_tmp, db) = setup();
1946        let (rows, count) =
1947            query(&db, "FROM blocks WHERE n_tx >= 8 ORDER BY height LIMIT 2").unwrap();
1948        assert_eq!(count, 2, "both matching rows must survive the limit");
1949        let heights: Vec<u64> = rows.iter()
1950            .filter_map(|r| r["height"].as_u64())
1951            .collect();
1952        assert_eq!(heights, vec![4, 5]);
1953        // And the same shape DESC — top match first.
1954        let (rows_d, _) =
1955            query(&db, "FROM blocks WHERE n_tx >= 8 ORDER BY height DESC LIMIT 1").unwrap();
1956        assert_eq!(rows_d.len(), 1);
1957        assert_eq!(rows_d[0]["height"], 5);
1958    }
1959
1960    // ── Predicate parity (3.3.0) ─────────────────────────────────────────────
1961    //
1962    // setup() gives blocks 1..=5 with height = h, hash = "000{h}",
1963    // n_tx = h * 2. Every test below asserts against that fixture.
1964
1965    /// A second fixture with string fields and a sparse column, for LIKE and
1966    /// IS NULL. `miner` is absent on one row on purpose.
1967    fn setup_text() -> (tempfile::TempDir, Db) {
1968        let dir = tempdir().unwrap();
1969        let db = Db::open(dir.path(), None).unwrap();
1970        let rows = [
1971            ("1", serde_json::json!({"status": "open",    "miner": "Acme Pool", "fee": 10})),
1972            ("2", serde_json::json!({"status": "pending", "miner": "acme solo", "fee": 20})),
1973            ("3", serde_json::json!({"status": "closed",  "miner": "Zenith",    "fee": 30})),
1974            ("4", serde_json::json!({"status": "open",    "fee": 40})),
1975            ("5", serde_json::json!({"status": "voided",  "miner": Value::Null, "fee": 50})),
1976        ];
1977        for (id, data) in rows {
1978            db.put("jobs", id, data, vec![], None, None).unwrap();
1979        }
1980        (dir, db)
1981    }
1982
1983    fn ids(rows: &[Value]) -> Vec<String> {
1984        let mut v: Vec<String> = rows.iter()
1985            .filter_map(|r| r["_id"].as_str().map(String::from))
1986            .collect();
1987        v.sort();
1988        v
1989    }
1990
1991    #[test]
1992    fn where_in_list() {
1993        let (_tmp, db) = setup();
1994        let (rows, _) = query(&db, "FROM blocks WHERE height IN (2, 4)").unwrap();
1995        assert_eq!(ids(&rows), vec!["2", "4"]);
1996    }
1997
1998    #[test]
1999    fn where_in_strings() {
2000        let (_tmp, db) = setup_text();
2001        let (rows, _) = query(&db, r#"FROM jobs WHERE status IN ("open", "closed")"#).unwrap();
2002        assert_eq!(ids(&rows), vec!["1", "3", "4"]);
2003    }
2004
2005    #[test]
2006    fn where_not_in() {
2007        let (_tmp, db) = setup();
2008        let (rows, _) = query(&db, "FROM blocks WHERE height NOT IN (1, 2, 3)").unwrap();
2009        assert_eq!(ids(&rows), vec!["4", "5"]);
2010    }
2011
2012    #[test]
2013    fn where_in_single_value_equals_eq() {
2014        let (_tmp, db) = setup();
2015        let (a, _) = query(&db, "FROM blocks WHERE height IN (3)").unwrap();
2016        let (b, _) = query(&db, "FROM blocks WHERE height = 3").unwrap();
2017        assert_eq!(ids(&a), ids(&b));
2018    }
2019
2020    #[test]
2021    fn where_between_is_inclusive() {
2022        let (_tmp, db) = setup();
2023        let (rows, _) = query(&db, "FROM blocks WHERE height BETWEEN 2 AND 4").unwrap();
2024        // SQL BETWEEN includes both bounds — 2 and 4 must be present.
2025        assert_eq!(ids(&rows), vec!["2", "3", "4"]);
2026    }
2027
2028    #[test]
2029    fn where_not_between() {
2030        let (_tmp, db) = setup();
2031        let (rows, _) = query(&db, "FROM blocks WHERE height NOT BETWEEN 2 AND 4").unwrap();
2032        assert_eq!(ids(&rows), vec!["1", "5"]);
2033    }
2034
2035    /// The AND inside BETWEEN belongs to BETWEEN, not to the conjunction
2036    /// parser. If parse_and grabbed it first, this query would fail to parse
2037    /// or silently lose the second bound.
2038    #[test]
2039    fn between_and_does_not_swallow_the_conjunction() {
2040        let (_tmp, db) = setup();
2041        let (rows, _) = query(
2042            &db, "FROM blocks WHERE height BETWEEN 2 AND 4 AND n_tx > 4").unwrap();
2043        // heights 2,3,4 then n_tx > 4 (n_tx = h*2) leaves 3 and 4.
2044        assert_eq!(ids(&rows), vec!["3", "4"]);
2045    }
2046
2047    #[test]
2048    fn where_like_prefix_suffix_and_infix() {
2049        let (_tmp, db) = setup_text();
2050        let (pre, _) = query(&db, r#"FROM jobs WHERE miner LIKE "Acme%""#).unwrap();
2051        assert_eq!(ids(&pre), vec!["1"]);
2052        let (suf, _) = query(&db, r#"FROM jobs WHERE miner LIKE "%Pool""#).unwrap();
2053        assert_eq!(ids(&suf), vec!["1"]);
2054        let (inf, _) = query(&db, r#"FROM jobs WHERE status LIKE "%pen%""#).unwrap();
2055        assert_eq!(ids(&inf), vec!["1", "2", "4"]);   // open, pending, open
2056    }
2057
2058    #[test]
2059    fn where_like_underscore_matches_exactly_one_char() {
2060        let (_tmp, db) = setup_text();
2061        let (rows, _) = query(&db, r#"FROM jobs WHERE status LIKE "open_""#).unwrap();
2062        assert!(rows.is_empty(), "`open_` must not match the 4-char value `open`");
2063        let (rows2, _) = query(&db, r#"FROM jobs WHERE status LIKE "ope_""#).unwrap();
2064        assert_eq!(ids(&rows2), vec!["1", "4"]);
2065    }
2066
2067    #[test]
2068    fn where_ilike_is_case_insensitive_and_like_is_not() {
2069        let (_tmp, db) = setup_text();
2070        let (ci, _) = query(&db, r#"FROM jobs WHERE miner ILIKE "acme%""#).unwrap();
2071        assert_eq!(ci.len(), 2, "ILIKE matches both `Acme Pool` and `acme solo`");
2072        let (cs, _) = query(&db, r#"FROM jobs WHERE miner LIKE "acme%""#).unwrap();
2073        assert_eq!(ids(&cs), vec!["2"], "LIKE stays case-sensitive");
2074    }
2075
2076    /// The backtracking path: multiple `%` with literals between them, where a
2077    /// greedy first match must be given back for the pattern to succeed.
2078    #[test]
2079    fn like_backtracks_across_multiple_wildcards() {
2080        assert!(like_match("abcabcabd", "%abc%abd", false));
2081        assert!(like_match("aaa", "%a", false));
2082        assert!(like_match("", "%", false));
2083        assert!(like_match("x", "%%%", false));
2084        assert!(!like_match("abc", "%abd", false));
2085        assert!(!like_match("ab", "ab_", false));
2086        assert!(like_match("héllo wörld", "h_llo w%d", false));
2087    }
2088
2089    // ── `~` / `!~` — the operator psql's catalogue filters need ─────────────
2090
2091    #[test]
2092    fn regex_anchors_behave_as_posix_says() {
2093        // THE case this exists for: psql's \dn sends `nspname !~ '^pg_'`.
2094        assert!(regex_match("pg_catalog", "^pg_", false));
2095        assert!(regex_match("pg_toast_1", "^pg_toast", false));
2096        assert!(!regex_match("public", "^pg_", false));
2097        // `^` only anchors at position 0 — a schema merely CONTAINING pg_ is
2098        // not a system schema, and treating it as one would hide a user's data.
2099        assert!(!regex_match("my_pg_stuff", "^pg_", false));
2100
2101        assert!(regex_match("report.sql", "sql$", false));
2102        assert!(!regex_match("sql_report", "sql$", false));
2103        // Anchored at both ends is an exact match.
2104        assert!(regex_match("public", "^public$", false));
2105        assert!(!regex_match("public2", "^public$", false));
2106        // Unanchored is a substring search.
2107        assert!(regex_match("xxpg_yy", "pg_", false));
2108        assert!(!regex_match("xxqg_yy", "pg_", false));
2109    }
2110
2111    #[test]
2112    fn regex_dot_matches_exactly_one_character() {
2113        assert!(regex_match("abc", "a.c", false));
2114        assert!(!regex_match("ac", "a.c", false), "`.` is one char, not zero");
2115        assert!(!regex_match("abbc", "a.c", false), "`.` is one char, not many");
2116        // Operates on chars, so a multi-byte value matches correctly.
2117        assert!(regex_match("héllo", "h.llo", false));
2118    }
2119
2120    #[test]
2121    fn regex_case_insensitivity_is_opt_in() {
2122        assert!(regex_match("PG_CATALOG", "^pg_", true));
2123        assert!(!regex_match("PG_CATALOG", "^pg_", false),
2124                "`~` is case SENSITIVE; only `~*` folds case");
2125    }
2126
2127    #[test]
2128    fn an_empty_regex_matches_anything() {
2129        // POSIX says so, and `$` alone is an empty anchored pattern.
2130        assert!(regex_match("anything", "", false));
2131        assert!(regex_match("", "", false));
2132        assert!(regex_match("x", "$", false));
2133    }
2134
2135    #[test]
2136    fn regex_groups_alternation_classes_and_quantifiers_match_as_ERE_says() {
2137        // THE case that forced the wider subset: `\d orders` sends
2138        // `relname ~ '^(orders)$'`, and `\d ord*` sends `^(ord.*)$`.
2139        assert!(regex_match("orders", "^(orders)$", false));
2140        assert!(!regex_match("orders2", "^(orders)$", false));
2141        assert!(regex_match("orders", "^(ord.*)$", false));
2142        assert!(regex_match("ord", "^(ord.*)$", false), "`.*` may match nothing");
2143        assert!(!regex_match("xord", "^(ord.*)$", false));
2144        // alternation, inside and outside a group
2145        assert!(regex_match("drivers", "^(orders|drivers)$", false));
2146        assert!(!regex_match("riders", "^(orders|drivers)$", false));
2147        assert!(regex_match("b", "a|b", false));
2148        // quantifiers are greedy and backtrack
2149        assert!(regex_match("aaab", "^a+b$", false));
2150        assert!(!regex_match("b", "^a+b$", false));
2151        assert!(regex_match("b", "^a*b$", false));
2152        assert!(regex_match("ab", "^a?b$", false));
2153        assert!(!regex_match("aab", "^a?b$", false));
2154        assert!(regex_match("aXb", "^a.+b$", false));
2155        // classes, ranges, negation, and a trailing literal `-`
2156        assert!(regex_match("pg_toast_9", "^pg_[a-z]+_[0-9]$", false));
2157        assert!(!regex_match("pg_toast_x", "^pg_[a-z]+_[0-9]$", false));
2158        assert!(regex_match("x", "^[^0-9]$", false));
2159        assert!(!regex_match("5", "^[^0-9]$", false));
2160        assert!(regex_match("a-b", "^a[-]b$", false));
2161        // an escape is the literal character, so `\.` is a dot and not "any"
2162        assert!(regex_match("a.b", "^a\\.b$", false));
2163        assert!(!regex_match("axb", "^a\\.b$", false));
2164        assert!(regex_match("(x)", "^\\(x\\)$", false));
2165        // `()*` must not loop forever: an empty repetition consumes nothing
2166        assert!(regex_match("q", "^()*q$", false));
2167        // operates on chars
2168        assert!(regex_match("héllo", "^h.l+o$", false));
2169    }
2170
2171    #[test]
2172    fn an_unsupported_regex_construct_is_REFUSED_BY_NAME_not_approximated() {
2173        // Matching `a{2,3}` approximately would silently include or exclude
2174        // rows, and a wrong catalogue listing looks exactly like a correct
2175        // one. So the parser refuses and names the construct.
2176        for (pat, needle) in [
2177            ("a{2}", "interval"),
2178            ("[[:alpha:]]", "POSIX character class"),
2179            ("(a)\\1", "back-reference"),
2180            ("\\d+", "shorthand class"),
2181            ("(ab", "unmatched '('"),
2182            ("ab)", "unmatched ')'"),
2183            ("[ab", "unmatched '['"),
2184            ("*a", "nothing to repeat"),
2185            ("[z-a]", "reversed"),
2186        ] {
2187            let why = regex_error(pat).unwrap_or_else(|| {
2188                panic!("{:?} must be refused, not matched approximately", pat)
2189            });
2190            assert!(why.contains(needle), "{:?}: {:?} should name {:?}", pat, why, needle);
2191            // And the matcher never answers for a pattern the parser refused.
2192            assert!(!regex_match("aa", pat, false));
2193        }
2194        for pat in ["^pg_", "sql$", "^public$", "a.c", "plain", "", "^(orders)$",
2195                    "a+b", "a*b", "a?b", "[ab]", "(a|b)", "a\\.b", "a[-]b"] {
2196            assert_eq!(regex_error(pat), None, "{:?} is in the subset", pat);
2197        }
2198    }
2199
2200    #[test]
2201    fn the_regex_operators_parse_in_all_four_spellings() {
2202        for (nql, negated, ci) in [
2203            (r#"FROM t WHERE nspname ~ "^pg_""#,   false, false),
2204            (r#"FROM t WHERE nspname ~* "^pg_""#,  false, true),
2205            (r#"FROM t WHERE nspname !~ "^pg_""#,  true,  false),
2206            (r#"FROM t WHERE nspname !~* "^pg_""#, true,  true),
2207        ] {
2208            let q = parse(nql).unwrap_or_else(|e| panic!("{}: {}", nql, e));
2209            match q.where_.expect("a predicate") {
2210                Pred::Regex { field, pattern, negated: n, ci: c } => {
2211                    assert_eq!(field, "nspname");
2212                    assert_eq!(pattern, "^pg_");
2213                    assert_eq!((n, c), (negated, ci), "{}", nql);
2214                }
2215                other => panic!("{} parsed as {:?}", nql, other),
2216            }
2217        }
2218    }
2219
2220    #[test]
2221    fn a_bad_regex_is_rejected_at_parse_time_with_the_offending_char() {
2222        let e = parse(r#"FROM t WHERE x ~ "a{2}""#).unwrap_err().to_string();
2223        assert!(e.contains("interval"), "the error must name the construct: {}", e);
2224        assert!(e.contains("refused"), "{}", e);
2225    }
2226
2227    #[test]
2228    fn a_regex_over_a_missing_field_is_false_in_both_polarities() {
2229        // SQL three-valued logic, matching LIKE and matching Postgres. psql's
2230        // catalogue filters depend on `!~` NOT resurrecting absent rows.
2231        let (_tmp, db) = setup_items();
2232        let (m, _) = query(&db, r#"FROM items WHERE nosuchfield ~ "x""#).unwrap();
2233        assert!(m.is_empty());
2234        let (n, _) = query(&db, r#"FROM items WHERE nosuchfield !~ "x""#).unwrap();
2235        assert!(n.is_empty(), "NOT over NULL must not match either");
2236    }
2237
2238    #[test]
2239    fn the_regex_operator_works_end_to_end_over_stored_documents() {
2240        let (_tmp, db) = setup_items();
2241        let (all, _) = query(&db, "FROM items").unwrap();
2242        let want: Vec<String> = all.iter()
2243            .filter_map(|r| r["_id"].as_str().map(str::to_string)).collect();
2244        // `_id` on every seeded item is non-empty, so an empty pattern matches
2245        // all of them — a control proving the operator reaches the executor.
2246        let (got, _) = query(&db, r#"FROM items WHERE _id ~ """#).unwrap();
2247        assert_eq!(got.len(), want.len());
2248        // And `!~` over the same pattern matches none.
2249        let (none, _) = query(&db, r#"FROM items WHERE _id !~ """#).unwrap();
2250        assert!(none.is_empty());
2251    }
2252
2253    #[test]
2254    fn where_not_like() {
2255        let (_tmp, db) = setup_text();
2256        let (rows, _) = query(&db, r#"FROM jobs WHERE status NOT LIKE "open""#).unwrap();
2257        assert_eq!(ids(&rows), vec!["2", "3", "5"]);
2258    }
2259
2260    /// NOT LIKE over a NULL/absent field stays false, as in SQL: a predicate
2261    /// over NULL is never true in either polarity. Rows 4 (absent) and 5
2262    /// (explicit null) must appear in NEITHER `LIKE` nor `NOT LIKE`.
2263    #[test]
2264    fn like_over_null_is_false_in_both_polarities() {
2265        let (_tmp, db) = setup_text();
2266        let (pos, _) = query(&db, r#"FROM jobs WHERE miner LIKE "%""#).unwrap();
2267        let (neg, _) = query(&db, r#"FROM jobs WHERE miner NOT LIKE "%""#).unwrap();
2268        assert!(!ids(&pos).contains(&"4".to_string()));
2269        assert!(!ids(&neg).contains(&"4".to_string()));
2270        assert!(!ids(&pos).contains(&"5".to_string()));
2271        assert!(!ids(&neg).contains(&"5".to_string()));
2272    }
2273
2274    /// Absent and explicitly-null are the same observable state in a
2275    /// schemaless store, so IS NULL must catch both.
2276    #[test]
2277    fn where_is_null_catches_absent_and_explicit_null() {
2278        let (_tmp, db) = setup_text();
2279        let (rows, _) = query(&db, "FROM jobs WHERE miner IS NULL").unwrap();
2280        assert_eq!(ids(&rows), vec!["4", "5"]);
2281    }
2282
2283    #[test]
2284    fn where_is_not_null() {
2285        let (_tmp, db) = setup_text();
2286        let (rows, _) = query(&db, "FROM jobs WHERE miner IS NOT NULL").unwrap();
2287        assert_eq!(ids(&rows), vec!["1", "2", "3"]);
2288    }
2289
2290    #[test]
2291    fn where_or() {
2292        let (_tmp, db) = setup();
2293        let (rows, _) = query(&db, "FROM blocks WHERE height = 1 OR height = 5").unwrap();
2294        assert_eq!(ids(&rows), vec!["1", "5"]);
2295    }
2296
2297    /// AND binds tighter than OR, so this is `a OR (b AND c)` and NOT
2298    /// `(a OR b) AND c`. With the wrong precedence the result would be [5].
2299    #[test]
2300    fn and_binds_tighter_than_or() {
2301        let (_tmp, db) = setup();
2302        let (rows, _) = query(
2303            &db, "FROM blocks WHERE height = 1 OR height = 5 AND n_tx = 10").unwrap();
2304        assert_eq!(ids(&rows), vec!["1", "5"]);
2305        let (rows2, _) = query(
2306            &db, "FROM blocks WHERE height = 1 OR height = 5 AND n_tx = 99").unwrap();
2307        assert_eq!(ids(&rows2), vec!["1"], "the AND arm must not match");
2308    }
2309
2310    /// Parentheses must be able to override that precedence.
2311    #[test]
2312    fn parens_override_precedence() {
2313        let (_tmp, db) = setup();
2314        let (rows, _) = query(
2315            &db, "FROM blocks WHERE (height = 1 OR height = 5) AND n_tx = 10").unwrap();
2316        assert_eq!(ids(&rows), vec!["5"]);
2317    }
2318
2319    #[test]
2320    fn nested_parens() {
2321        let (_tmp, db) = setup();
2322        let (rows, _) = query(
2323            &db,
2324            "FROM blocks WHERE ((height >= 2 AND height <= 4) OR height = 1) AND n_tx != 6",
2325        ).unwrap();
2326        assert_eq!(ids(&rows), vec!["1", "2", "4"]);
2327    }
2328
2329    #[test]
2330    fn not_negates_a_group() {
2331        let (_tmp, db) = setup();
2332        let (rows, _) = query(&db, "FROM blocks WHERE NOT (height > 2)").unwrap();
2333        assert_eq!(ids(&rows), vec!["1", "2"]);
2334    }
2335
2336    /// Prefix NOT before a bare comparison, as SQL allows. Distinct from the
2337    /// INFIX `field NOT <op>` form, which is a syntax error — only NOT IN /
2338    /// NOT BETWEEN / NOT LIKE exist in that position.
2339    #[test]
2340    fn prefix_not_before_a_comparison() {
2341        let (_tmp, db) = setup();
2342        let (rows, _) = query(&db, "FROM blocks WHERE NOT height = 1").unwrap();
2343        assert_eq!(ids(&rows), vec!["2", "3", "4", "5"]);
2344        let (double, _) = query(&db, "FROM blocks WHERE NOT NOT height = 1").unwrap();
2345        assert_eq!(ids(&double), vec!["1"]);
2346        let (mixed, _) = query(&db, "FROM blocks WHERE NOT height = 1 AND height < 4").unwrap();
2347        assert_eq!(ids(&mixed), vec!["2", "3"]);
2348    }
2349
2350    /// `_id = "x"` takes an O(1) index path. Under an OR it does not constrain
2351    /// the result set, so using it as a point lookup would drop every row the
2352    /// other arm matched. Guards the id_point_lookup AND-only descent.
2353    #[test]
2354    fn id_equality_under_or_does_not_become_a_point_lookup() {
2355        let (_tmp, db) = setup();
2356        let (rows, _) = query(&db, r#"FROM blocks WHERE _id = "1" OR height > 3"#).unwrap();
2357        assert_eq!(ids(&rows), vec!["1", "4", "5"],
2358                   "the OR arm must survive the id fast path");
2359    }
2360
2361    /// The fast path is still taken when the equality is a genuine conjunct.
2362    #[test]
2363    fn id_equality_under_and_still_point_looks_up() {
2364        let (_tmp, db) = setup();
2365        let (hit, _) = query(&db, r#"FROM blocks WHERE _id = "3" AND n_tx = 6"#).unwrap();
2366        assert_eq!(ids(&hit), vec!["3"]);
2367        let (miss, _) = query(&db, r#"FROM blocks WHERE _id = "3" AND n_tx = 999"#).unwrap();
2368        assert!(miss.is_empty(), "the second conjunct must still be applied");
2369    }
2370
2371    #[test]
2372    fn metadata_fields_are_filterable() {
2373        let (_tmp, db) = setup();
2374        let (rows, _) = query(&db, "FROM blocks WHERE _seq >= 0 AND _coll = blocks").unwrap();
2375        assert_eq!(rows.len(), 5);
2376
2377        // Cut above the FIRST row's seq rather than above a hardcoded 0. The
2378        // absolute value moved when collection registration became a real
2379        // write (seq 0 is now the `_nedb.collections` record), and a test that
2380        // pins absolute sequence numbers is testing the write order of the
2381        // engine's bookkeeping, not whether `_seq` is filterable.
2382        let first = rows.iter()
2383            .filter_map(|r| r.get("_seq").and_then(|v| v.as_u64()))
2384            .min()
2385            .expect("five rows carrying _seq");
2386        let (tail, _) = query(&db, &format!("FROM blocks WHERE _seq > {}", first)).unwrap();
2387        assert_eq!(tail.len(), 4);
2388    }
2389
2390    /// The engine's own bookkeeping is not part of anybody's query results.
2391    #[test]
2392    fn a_reserved_collection_never_leaks_into_a_user_query() {
2393        let (_tmp, db) = setup();
2394        let (rows, _) = query(&db, "FROM blocks").unwrap();
2395        assert!(
2396            rows.iter().all(|r| r.get("_coll").and_then(|v| v.as_str()) == Some("blocks")),
2397            "a query for one collection returned rows from another"
2398        );
2399        assert!(
2400            !db.collections().iter().any(|c| crate::namespace::is_reserved(c)),
2401            "the registry is not a user collection"
2402        );
2403    }
2404
2405    #[test]
2406    fn combined_with_order_and_limit() {
2407        let (_tmp, db) = setup();
2408        let (rows, _) = query(
2409            &db,
2410            "FROM blocks WHERE height IN (1, 3, 5) ORDER BY height DESC LIMIT 2",
2411        ).unwrap();
2412        let heights: Vec<u64> = rows.iter().filter_map(|r| r["height"].as_u64()).collect();
2413        assert_eq!(heights, vec![5, 3]);
2414    }
2415
2416    // ── Strictness: a query the engine cannot honour must FAIL, not lie ──────
2417
2418    /// The headline regression. `_ => { self.advance(); }` meant an
2419    /// unimplemented or misspelled clause was dropped and a DIFFERENT query
2420    /// was answered. Each of these previously returned rows.
2421    #[test]
2422    fn unknown_clauses_are_errors_not_silent_skips() {
2423        let (_tmp, db) = setup();
2424        for bad in [
2425            "FROM blocks ORDRE BY height",       // typo
2426            "FROM blocks WHERE height > 3 JUNK", // trailing garbage
2427            "FROM blocks SELECT height",         // wrong dialect
2428            "FROM blocks LIMIT",                 // missing count
2429            "FROM blocks OFFSET",                // missing count
2430            "FROM blocks ORDER BY",              // missing key
2431            "FROM blocks ORDER BY height,",      // trailing comma
2432        ] {
2433            assert!(query(&db, bad).is_err(), "`{}` must be rejected, not silently reinterpreted", bad);
2434        }
2435    }
2436
2437    #[test]
2438    fn malformed_predicates_are_errors() {
2439        let (_tmp, db) = setup();
2440        for bad in [
2441            "FROM blocks WHERE height >",            // missing value
2442            "FROM blocks WHERE height IN (",         // unterminated list
2443            "FROM blocks WHERE height IN ()",        // empty list
2444            "FROM blocks WHERE height BETWEEN 1",    // missing AND high
2445            "FROM blocks WHERE height BETWEEN 1 3",  // missing AND
2446            "FROM blocks WHERE (height = 1",         // unbalanced paren
2447            "FROM blocks WHERE height IS 3",         // IS without NULL
2448            "FROM blocks WHERE height NOT = 1",      // infix NOT before a comparison op
2449            "FROM blocks WHERE height LIKE",         // missing pattern
2450        ] {
2451            assert!(query(&db, bad).is_err(), "`{}` must be a parse error", bad);
2452        }
2453    }
2454
2455    /// ASC used to survive only because unknown tokens were skipped. Now that
2456    /// skipping is gone it has to be a real keyword, and the pre-existing
2457    /// `order_by_limit` test above depends on it.
2458    #[test]
2459    fn asc_is_accepted_explicitly() {
2460        let (_tmp, db) = setup();
2461        let (asc, _) = query(&db, "FROM blocks ORDER BY height ASC").unwrap();
2462        let (plain, _) = query(&db, "FROM blocks ORDER BY height").unwrap();
2463        assert_eq!(asc[0]["height"], 1);
2464        assert_eq!(plain[0]["height"], 1);
2465    }
2466
2467    /// Lowercase and mixed-case keywords must keep working — the lexer
2468    /// uppercases before matching, and the new keywords must be no different.
2469    #[test]
2470    fn new_keywords_are_case_insensitive() {
2471        let (_tmp, db) = setup();
2472        let (rows, _) = query(&db, "from blocks where height between 2 and 3").unwrap();
2473        assert_eq!(ids(&rows), vec!["2", "3"]);
2474        let (rows2, _) = query(&db, "FROM blocks Where height In (1) Or height In (2)").unwrap();
2475        assert_eq!(ids(&rows2), vec!["1", "2"]);
2476    }
2477
2478    #[test]
2479    fn group_by_count() {
2480        let (_tmp, db) = setup();
2481        let (rows, _) = query(&db, "FROM blocks GROUP BY n_tx COUNT").unwrap();
2482        assert_eq!(rows.len(), 5); // all unique n_tx values
2483    }
2484
2485    // ── Indexed range / point scans (3.3.0) ─────────────────────────────────
2486    //
2487    // The load-bearing property is EQUIVALENCE: an indexed query and the same
2488    // query without an index must return the same rows. The planner is allowed
2489    // to be imprecise (it only has to produce a superset — the full predicate
2490    // re-runs on the candidates) but it is never allowed to be wrong.
2491    //
2492    // Every test below therefore runs the same query against two databases
2493    // holding identical data, one indexed and one not, and compares.
2494
2495    /// Build two identical databases, one with sorted indexes on `fields`.
2496    fn twin(fields: &[&str]) -> (tempfile::TempDir, tempfile::TempDir, Db, Db) {
2497        let d1 = tempdir().unwrap();
2498        let d2 = tempdir().unwrap();
2499        let indexed = Db::open(d1.path(), None).unwrap();
2500        let plain = Db::open(d2.path(), None).unwrap();
2501        for f in fields {
2502            indexed.create_sorted_index("t", f);
2503        }
2504        // Deliberately messy: duplicate fees, a missing field, a null, a
2505        // string column, and an out-of-order insert sequence.
2506        let rows: Vec<(String, Value)> = (0..40u64).map(|i| {
2507            let mut o = serde_json::Map::new();
2508            if i % 7 != 0 {
2509                o.insert("fee".into(), json!(i % 13));
2510            }
2511            if i % 11 == 0 {
2512                o.insert("note".into(), Value::Null);
2513            } else {
2514                o.insert("note".into(), json!(format!("n{}", i % 5)));
2515            }
2516            o.insert("rank".into(), json!(40 - i));
2517            (i.to_string(), Value::Object(o))
2518        }).collect();
2519        for (id, doc) in &rows {
2520            indexed.put("t", id, doc.clone(), vec![], None, None).unwrap();
2521            plain.put("t", id, doc.clone(), vec![], None, None).unwrap();
2522        }
2523        (d1, d2, indexed, plain)
2524    }
2525
2526    fn same(a: &Db, b: &Db, nql: &str) -> (Vec<String>, Vec<String>) {
2527        let ga = {
2528            let (rows, _) = query(a, nql).unwrap();
2529            let mut v: Vec<String> = rows.iter()
2530                .filter_map(|r| r["_id"].as_str().map(String::from)).collect();
2531            v.sort(); v
2532        };
2533        let gb = {
2534            let (rows, _) = query(b, nql).unwrap();
2535            let mut v: Vec<String> = rows.iter()
2536                .filter_map(|r| r["_id"].as_str().map(String::from)).collect();
2537            v.sort(); v
2538        };
2539        (ga, gb)
2540    }
2541
2542    #[test]
2543    fn indexed_and_unindexed_agree_on_every_predicate_shape() {
2544        let (_t1, _t2, idx, plain) = twin(&["fee", "note", "rank"]);
2545        for nql in [
2546            // ranges — the shapes the index now serves
2547            "FROM t WHERE fee > 5",
2548            "FROM t WHERE fee >= 5",
2549            "FROM t WHERE fee < 5",
2550            "FROM t WHERE fee <= 5",
2551            "FROM t WHERE fee = 5",
2552            "FROM t WHERE fee BETWEEN 3 AND 8",
2553            "FROM t WHERE fee NOT BETWEEN 3 AND 8",
2554            "FROM t WHERE fee IN (1, 5, 9)",
2555            "FROM t WHERE fee NOT IN (1, 5, 9)",
2556            "FROM t WHERE fee != 5",
2557            // merged bounds on one field
2558            "FROM t WHERE fee > 3 AND fee < 9",
2559            "FROM t WHERE fee >= 3 AND fee <= 9",
2560            "FROM t WHERE fee > 3 AND fee < 9 AND fee != 5",
2561            "FROM t WHERE fee BETWEEN 2 AND 10 AND fee > 6",
2562            // two indexed fields — the planner must pick one and stay correct
2563            "FROM t WHERE fee > 5 AND rank < 20",
2564            "FROM t WHERE fee IN (2, 3) AND rank > 10",
2565            "FROM t WHERE fee = 4 AND rank = 8",
2566            // the absent-field cases, where a naive index scan inverts the answer
2567            "FROM t WHERE fee IS NULL",
2568            "FROM t WHERE fee IS NOT NULL",
2569            "FROM t WHERE note IS NULL",
2570            "FROM t WHERE note IS NOT NULL",
2571            "FROM t WHERE fee IS NULL AND rank > 20",
2572            // predicates the index cannot serve, mixed with ones it can
2573            r#"FROM t WHERE note LIKE "n_""#,
2574            r#"FROM t WHERE fee > 5 AND note LIKE "n1""#,
2575            r#"FROM t WHERE note NOT LIKE "n1" AND fee < 4"#,
2576            // disjunction — must NOT be narrowed on one arm
2577            "FROM t WHERE fee > 11 OR rank > 38",
2578            "FROM t WHERE fee = 1 OR note IS NULL",
2579            "FROM t WHERE (fee > 11 OR rank > 38) AND rank < 39",
2580            "FROM t WHERE fee IN (1) OR fee IN (2)",
2581            // negation
2582            "FROM t WHERE NOT (fee > 5)",
2583            "FROM t WHERE NOT (fee IN (1, 2))",
2584            "FROM t WHERE NOT (fee > 5) AND rank < 30",
2585            // with shaping on top
2586            "FROM t WHERE fee > 5 ORDER BY rank DESC LIMIT 5",
2587            "FROM t WHERE fee BETWEEN 2 AND 8 ORDER BY fee, rank DESC",
2588            "FROM t WHERE fee > 5 GROUP BY note COUNT",
2589            "FROM t WHERE fee > 5 COUNT",
2590            "FROM t WHERE fee > 5 ORDER BY rank LIMIT 3 OFFSET 2",
2591            // empty results
2592            "FROM t WHERE fee > 9999",
2593            "FROM t WHERE fee IN (9999)",
2594            "FROM t WHERE fee BETWEEN 100 AND 200",
2595        ] {
2596            let (a, b) = same(&idx, &plain, nql);
2597            assert_eq!(a, b, "indexed and unindexed disagree on `{}`", nql);
2598        }
2599    }
2600
2601    /// Ordering, not just membership, must survive the index path — the
2602    /// candidates arrive in index order of the PREDICATE field, which is not
2603    /// the requested sort order, so the post-filter sort has to still run.
2604    #[test]
2605    fn index_path_still_honours_order_by() {
2606        let (_t1, _t2, idx, plain) = twin(&["fee", "rank"]);
2607        for nql in [
2608            "FROM t WHERE fee > 4 ORDER BY rank",
2609            "FROM t WHERE fee > 4 ORDER BY rank DESC",
2610            "FROM t WHERE fee > 4 ORDER BY note, rank DESC",
2611            "FROM t WHERE fee BETWEEN 2 AND 9 ORDER BY rank LIMIT 4",
2612            "FROM t WHERE fee IN (3, 6) ORDER BY rank DESC LIMIT 2",
2613        ] {
2614            let ra = query(&idx, nql).unwrap().0;
2615            let rb = query(&plain, nql).unwrap().0;
2616            let ia: Vec<&str> = ra.iter().filter_map(|r| r["_id"].as_str()).collect();
2617            let ib: Vec<&str> = rb.iter().filter_map(|r| r["_id"].as_str()).collect();
2618            assert_eq!(ia, ib, "row ORDER differs on `{}`", nql);
2619        }
2620    }
2621
2622    /// An ordering comparison against a missing field is never true.
2623    ///
2624    /// OrderedValue sorts Null below every number, so `<` and `<=` reported
2625    /// that a document with NO `fee` field satisfied `WHERE fee < 5` — while
2626    /// `>` and `>=` excluded it. That asymmetry was the tell. The Python
2627    /// reference has always excluded it, so this was a cross-engine
2628    /// divergence as well as a wrong answer, and it meant the scan path and
2629    /// the index path disagreed depending on whether an index existed.
2630    #[test]
2631    fn an_ordering_comparison_against_a_missing_field_is_false() {
2632        let dir = tempdir().unwrap();
2633        let db = Db::open(dir.path(), None).unwrap();
2634        db.put("t", "has", json!({"fee": 1}), vec![], None, None).unwrap();
2635        db.put("t", "none", json!({"other": 1}), vec![], None, None).unwrap();
2636        db.put("t", "null", json!({"fee": Value::Null}), vec![], None, None).unwrap();
2637
2638        for nql in ["FROM t WHERE fee < 5", "FROM t WHERE fee <= 5"] {
2639            let (r, _) = query(&db, nql).unwrap();
2640            let ids: Vec<&str> = r.iter().filter_map(|x| x["_id"].as_str()).collect();
2641            assert_eq!(ids, vec!["has"],
2642                       "`{}` must not match a row whose fee is absent or null", nql);
2643        }
2644        for nql in ["FROM t WHERE fee > 0", "FROM t WHERE fee >= 0"] {
2645            let (r, _) = query(&db, nql).unwrap();
2646            let ids: Vec<&str> = r.iter().filter_map(|x| x["_id"].as_str()).collect();
2647            assert_eq!(ids, vec!["has"], "`{}`", nql);
2648        }
2649        // BETWEEN is built from >= and <=, so it inherits the rule.
2650        let (b, _) = query(&db, "FROM t WHERE fee BETWEEN 0 AND 9").unwrap();
2651        assert_eq!(b.len(), 1);
2652
2653        // = and != keep operating on null, exactly as the Python reference
2654        // does — its None guard sits deliberately AFTER those two arms.
2655        let (ne, _) = query(&db, "FROM t WHERE fee != 5").unwrap();
2656        assert_eq!(ne.len(), 3, "!= still matches absent and null fields");
2657        let (isnull, _) = query(&db, "FROM t WHERE fee = NULL").unwrap();
2658        assert_eq!(isnull.len(), 2, "absent and explicit-null both equal NULL");
2659
2660        // And the same answers with an index present — the two paths agreeing
2661        // is the reason this fix was required, not merely desirable.
2662        let d2 = tempdir().unwrap();
2663        let idx = Db::open(d2.path(), None).unwrap();
2664        idx.create_sorted_index("t", "fee");
2665        idx.put("t", "has", json!({"fee": 1}), vec![], None, None).unwrap();
2666        idx.put("t", "none", json!({"other": 1}), vec![], None, None).unwrap();
2667        idx.put("t", "null", json!({"fee": Value::Null}), vec![], None, None).unwrap();
2668        for nql in ["FROM t WHERE fee < 5", "FROM t WHERE fee <= 5",
2669                    "FROM t WHERE fee > 0", "FROM t WHERE fee BETWEEN 0 AND 9"] {
2670            let (a, _) = query(&db, nql).unwrap();
2671            let (b, _) = query(&idx, nql).unwrap();
2672            let ia: Vec<&str> = a.iter().filter_map(|x| x["_id"].as_str()).collect();
2673            let ib: Vec<&str> = b.iter().filter_map(|x| x["_id"].as_str()).collect();
2674            assert_eq!(ia, ib, "indexed and unindexed disagree on `{}`", nql);
2675        }
2676    }
2677
2678    /// `IS NULL` must never touch this index. A document whose field is absent
2679    /// is not in the index for that field, so an index scan would return
2680    /// exactly the complement of the right answer — the worst possible failure
2681    /// for a filter, since it looks like a plausible result set.
2682    #[test]
2683    fn is_null_never_uses_the_index() {
2684        let (_t1, _t2, idx, plain) = twin(&["fee"]);
2685        let (a, b) = same(&idx, &plain, "FROM t WHERE fee IS NULL");
2686        assert_eq!(a, b);
2687        // 40 docs, every 7th missing `fee`: ids 0,7,14,21,28,35.
2688        assert_eq!(a, vec!["0", "14", "21", "28", "35", "7"]);
2689        assert!(!a.is_empty(), "the fixture must actually contain absent fields");
2690    }
2691
2692    /// A constraint under an OR does not restrict the result set, so the
2693    /// planner must not narrow on it. Both arms have to survive.
2694    #[test]
2695    fn a_disjunct_is_never_used_to_narrow() {
2696        let (_t1, _t2, idx, plain) = twin(&["fee", "rank"]);
2697        let nql = "FROM t WHERE fee = 1 OR rank = 40";
2698        let (a, b) = same(&idx, &plain, nql);
2699        assert_eq!(a, b);
2700        // rank = 40 is doc 0, which has NO `fee` field at all — so if the
2701        // planner had narrowed on the `fee` arm it would have been dropped.
2702        assert!(a.contains(&"0".to_string()),
2703                "the OR arm matching a doc with no indexed field must survive: {:?}", a);
2704        assert!(a.len() > 1, "both arms must contribute: {:?}", a);
2705    }
2706
2707    /// AS OF must not use the index: it holds CURRENT versions only, because a
2708    /// superseded hash is removed on overwrite. An index scan would answer a
2709    /// historical query with present-day rows.
2710    #[test]
2711    fn as_of_does_not_use_the_current_version_index() {
2712        let dir = tempdir().unwrap();
2713        let db = Db::open(dir.path(), None).unwrap();
2714        db.create_sorted_index("t", "fee");
2715        db.put("t", "a", json!({"fee": 5}), vec![], None, None).unwrap();
2716        let snap = db.put("t", "b", json!({"fee": 5}), vec![], None, None).unwrap().seq;
2717        // Move both out of the range the query asks for.
2718        db.put("t", "a", json!({"fee": 999}), vec![], None, None).unwrap();
2719        db.put("t", "b", json!({"fee": 999}), vec![], None, None).unwrap();
2720
2721        // At HEAD nothing matches fee = 5 any more.
2722        let (now, _) = query(&db, "FROM t WHERE fee = 5").unwrap();
2723        assert!(now.is_empty(), "current versions have fee 999: {:?}", now);
2724
2725        // AS OF the snapshot, both still had fee = 5. If the index served
2726        // this, it would return nothing.
2727        let (then, _) = query(&db, &format!("FROM t AS OF {} WHERE fee = 5", snap)).unwrap();
2728        let mut ids: Vec<&str> = then.iter().filter_map(|r| r["_id"].as_str()).collect();
2729        ids.sort();
2730        assert_eq!(ids, vec!["a", "b"], "AS OF must see the historical values");
2731
2732        // Same for a range and an IN.
2733        let (r, _) = query(&db, &format!("FROM t AS OF {} WHERE fee BETWEEN 1 AND 9", snap)).unwrap();
2734        assert_eq!(r.len(), 2);
2735        let (i, _) = query(&db, &format!("FROM t AS OF {} WHERE fee IN (5)", snap)).unwrap();
2736        assert_eq!(i.len(), 2);
2737    }
2738
2739    /// An overwritten row must not come back from the index.
2740    #[test]
2741    fn the_index_path_returns_current_versions_only() {
2742        let dir = tempdir().unwrap();
2743        let db = Db::open(dir.path(), None).unwrap();
2744        db.create_sorted_index("t", "fee");
2745        for i in 0..5u64 {
2746            db.put("t", &i.to_string(), json!({"fee": i}), vec![], None, None).unwrap();
2747        }
2748        db.put("t", "0", json!({"fee": 100}), vec![], None, None).unwrap();
2749
2750        let (low, _) = query(&db, "FROM t WHERE fee BETWEEN 0 AND 4").unwrap();
2751        let mut ids: Vec<&str> = low.iter().filter_map(|r| r["_id"].as_str()).collect();
2752        ids.sort();
2753        assert_eq!(ids, vec!["1", "2", "3", "4"],
2754                   "doc 0 moved to fee 100 and must not appear in 0..4");
2755
2756        let (high, _) = query(&db, "FROM t WHERE fee = 100").unwrap();
2757        assert_eq!(high.len(), 1);
2758        assert_eq!(high[0]["_id"], "0");
2759        assert_eq!(high[0]["fee"], json!(100), "the CURRENT value, not the old one");
2760    }
2761
2762    /// Duplicate values must not produce duplicate rows, and a value repeated
2763    /// across IN arms must be returned once.
2764    #[test]
2765    fn index_scans_do_not_duplicate_rows() {
2766        let dir = tempdir().unwrap();
2767        let db = Db::open(dir.path(), None).unwrap();
2768        db.create_sorted_index("t", "fee");
2769        for i in 0..6u64 {
2770            db.put("t", &i.to_string(), json!({"fee": i % 2}), vec![], None, None).unwrap();
2771        }
2772        let (dup, _) = query(&db, "FROM t WHERE fee IN (0, 0, 1, 1)").unwrap();
2773        assert_eq!(dup.len(), 6, "each row once despite repeated IN arms");
2774        let (r, _) = query(&db, "FROM t WHERE fee BETWEEN 0 AND 1").unwrap();
2775        assert_eq!(r.len(), 6);
2776        let mut ids: Vec<&str> = dup.iter().filter_map(|r| r["_id"].as_str()).collect();
2777        ids.sort();
2778        ids.dedup();
2779        assert_eq!(ids.len(), 6, "no duplicate _ids");
2780    }
2781
2782    /// A range over a string column, to prove the index is not numeric-only.
2783    #[test]
2784    fn index_ranges_work_on_strings() {
2785        let dir = tempdir().unwrap();
2786        let db = Db::open(dir.path(), None).unwrap();
2787        db.create_sorted_index("t", "name");
2788        for (i, n) in ["alpha", "bravo", "charlie", "delta", "echo"].iter().enumerate() {
2789            db.put("t", &i.to_string(), json!({"name": n}), vec![], None, None).unwrap();
2790        }
2791        let (r, _) = query(&db, r#"FROM t WHERE name BETWEEN "bravo" AND "delta""#).unwrap();
2792        let mut got: Vec<&str> = r.iter().filter_map(|x| x["name"].as_str()).collect();
2793        got.sort();
2794        assert_eq!(got, vec!["bravo", "charlie", "delta"]);
2795        let (gt, _) = query(&db, r#"FROM t WHERE name > "charlie""#).unwrap();
2796        assert_eq!(gt.len(), 2);
2797    }
2798
2799    /// Bounds must be merged into one walk, and the tighter bound must win
2800    /// regardless of the order the conjuncts appear in.
2801    #[test]
2802    fn same_field_bounds_are_merged_tightest_wins() {
2803        let (_t1, _t2, idx, plain) = twin(&["fee"]);
2804        for (a_nql, b_nql) in [
2805            ("FROM t WHERE fee > 2 AND fee > 6", "FROM t WHERE fee > 6"),
2806            ("FROM t WHERE fee > 6 AND fee > 2", "FROM t WHERE fee > 6"),
2807            ("FROM t WHERE fee < 9 AND fee < 4", "FROM t WHERE fee < 4"),
2808            ("FROM t WHERE fee BETWEEN 0 AND 12 AND fee >= 5 AND fee <= 7",
2809             "FROM t WHERE fee >= 5 AND fee <= 7"),
2810        ] {
2811            let (ia, _) = same(&idx, &plain, a_nql);
2812            let (ib, _) = same(&idx, &plain, b_nql);
2813            assert_eq!(ia, ib, "`{}` should equal `{}`", a_nql, b_nql);
2814        }
2815    }
2816
2817    /// The index only helps where it exists; an unindexed field must still
2818    /// answer correctly through the scan path.
2819    #[test]
2820    fn a_predicate_on_an_unindexed_field_still_answers() {
2821        let (_t1, _t2, idx, plain) = twin(&["fee"]);   // `rank` is NOT indexed
2822        for nql in [
2823            "FROM t WHERE rank > 30",
2824            "FROM t WHERE rank BETWEEN 10 AND 20",
2825            "FROM t WHERE rank IN (40, 39)",
2826            "FROM t WHERE rank > 30 AND fee > 2",
2827        ] {
2828            let (a, b) = same(&idx, &plain, nql);
2829            assert_eq!(a, b, "`{}`", nql);
2830        }
2831    }
2832
2833    /// Cardinality is reported off the index without reading any rows, which
2834    /// is what lets the planner compare two candidate indexes.
2835    #[test]
2836    fn range_cardinality_counts_without_reading() {
2837        let dir = tempdir().unwrap();
2838        let db = Db::open(dir.path(), None).unwrap();
2839        db.create_sorted_index("t", "fee");
2840        for i in 0..20u64 {
2841            db.put("t", &i.to_string(), json!({"fee": i}), vec![], None, None).unwrap();
2842        }
2843        assert_eq!(db.range_cardinality("t", "fee", None, None, true, true), Some(20));
2844        assert_eq!(
2845            db.range_cardinality("t", "fee", Some(&json!(5)), Some(&json!(9)), true, true),
2846            Some(5), "5..=9 inclusive is five values");
2847        assert_eq!(
2848            db.range_cardinality("t", "fee", Some(&json!(5)), Some(&json!(9)), false, false),
2849            Some(3), "exclusive bounds drop both ends");
2850        assert_eq!(
2851            db.range_cardinality("t", "fee", Some(&json!(18)), None, true, true),
2852            Some(2));
2853        assert_eq!(
2854            db.range_cardinality("t", "fee", Some(&json!(999)), None, true, true),
2855            Some(0), "an empty range is 0, not an error");
2856        // No index on this field at all.
2857        assert_eq!(db.range_cardinality("t", "nope", None, None, true, true), None);
2858    }
2859
2860    /// With two usable indexes the planner should choose the narrower range.
2861    /// Asserted through cardinality rather than by inspecting the plan, so the
2862    /// test pins the observable behaviour and not the implementation.
2863    #[test]
2864    fn the_narrower_index_is_preferred() {
2865        let dir = tempdir().unwrap();
2866        let db = Db::open(dir.path(), None).unwrap();
2867        db.create_sorted_index("t", "wide");
2868        db.create_sorted_index("t", "narrow");
2869        for i in 0..100u64 {
2870            db.put("t", &i.to_string(),
2871                   json!({"wide": i % 2, "narrow": i}), vec![], None, None).unwrap();
2872        }
2873        // `wide = 0` covers 50 rows; `narrow = 7` covers 1.
2874        let wide = db.range_cardinality("t", "wide", Some(&json!(0)), Some(&json!(0)), true, true);
2875        let narrow = db.range_cardinality("t", "narrow", Some(&json!(7)), Some(&json!(7)), true, true);
2876        assert_eq!(wide, Some(50));
2877        assert_eq!(narrow, Some(1));
2878        // The answer must be right whichever index is chosen.
2879        let (r, _) = query(&db, "FROM t WHERE wide = 0 AND narrow = 7").unwrap();
2880        assert!(r.is_empty(), "narrow 7 has wide 1, so nothing matches");
2881        let (r2, _) = query(&db, "FROM t WHERE wide = 0 AND narrow = 8").unwrap();
2882        assert_eq!(r2.len(), 1);
2883        assert_eq!(r2[0]["_id"], "8");
2884    }
2885
2886    // ── Result shaping (3.3.0): OFFSET, multi-key ORDER BY, HAVING, ─────────
2887    // ── bare aggregates, and the SQL pipeline order ─────────────────────────
2888
2889    fn heights(rows: &[Value]) -> Vec<u64> {
2890        rows.iter().filter_map(|r| r["height"].as_u64()).collect()
2891    }
2892
2893    #[test]
2894    fn offset_skips_result_rows() {
2895        let (_tmp, db) = setup();
2896        let (rows, _) = query(&db, "FROM blocks ORDER BY height OFFSET 2").unwrap();
2897        assert_eq!(heights(&rows), vec![3, 4, 5]);
2898    }
2899
2900    #[test]
2901    fn offset_with_limit_pages() {
2902        let (_tmp, db) = setup();
2903        // Page through 5 rows two at a time. Each page must be disjoint and
2904        // in order — the bug to catch is a pushdown that fetches only `limit`
2905        // rows and therefore returns page 1 for every page.
2906        let mut seen = vec![];
2907        for page in 0..3 {
2908            let (rows, _) = query(
2909                &db,
2910                &format!("FROM blocks ORDER BY height LIMIT 2 OFFSET {}", page * 2),
2911            ).unwrap();
2912            seen.extend(heights(&rows));
2913        }
2914        assert_eq!(seen, vec![1, 2, 3, 4, 5]);
2915    }
2916
2917    #[test]
2918    fn offset_past_the_end_is_an_empty_page() {
2919        let (_tmp, db) = setup();
2920        let (rows, count) = query(&db, "FROM blocks OFFSET 99").unwrap();
2921        assert!(rows.is_empty());
2922        assert_eq!(count, 0);
2923        let (zero, _) = query(&db, "FROM blocks OFFSET 0").unwrap();
2924        assert_eq!(zero.len(), 5, "OFFSET 0 skips nothing");
2925    }
2926
2927    #[test]
2928    fn offset_applies_after_the_filter() {
2929        let (_tmp, db) = setup();
2930        // n_tx = h*2, so `>= 6` matches heights 3,4,5. Offsetting by one must
2931        // skip the first MATCH, not the first row of the collection.
2932        let (rows, _) = query(
2933            &db, "FROM blocks WHERE n_tx >= 6 ORDER BY height OFFSET 1").unwrap();
2934        assert_eq!(heights(&rows), vec![4, 5]);
2935    }
2936
2937    #[test]
2938    fn order_by_multiple_keys() {
2939        let dir = tempdir().unwrap();
2940        let db = Db::open(dir.path(), None).unwrap();
2941        // Two statuses, each with several fees, so the second key has to do
2942        // real work to break the first key's ties.
2943        for (i, (s, f)) in [("open", 30), ("open", 10), ("closed", 20),
2944                            ("open", 20), ("closed", 5)].iter().enumerate() {
2945            db.put("t", &i.to_string(),
2946                serde_json::json!({"status": s, "fee": f}), vec![], None, None).unwrap();
2947        }
2948        let (rows, _) = query(&db, "FROM t ORDER BY status, fee DESC").unwrap();
2949        let got: Vec<(String, u64)> = rows.iter()
2950            .map(|r| (r["status"].as_str().unwrap().to_string(), r["fee"].as_u64().unwrap()))
2951            .collect();
2952        assert_eq!(got, vec![
2953            ("closed".into(), 20), ("closed".into(), 5),
2954            ("open".into(), 30), ("open".into(), 20), ("open".into(), 10),
2955        ]);
2956    }
2957
2958    #[test]
2959    fn order_by_mixed_directions() {
2960        let dir = tempdir().unwrap();
2961        let db = Db::open(dir.path(), None).unwrap();
2962        for (i, (a, b)) in [(1, 1), (1, 2), (2, 1), (2, 2)].iter().enumerate() {
2963            db.put("t", &i.to_string(),
2964                serde_json::json!({"a": a, "b": b}), vec![], None, None).unwrap();
2965        }
2966        let (rows, _) = query(&db, "FROM t ORDER BY a DESC, b ASC").unwrap();
2967        let got: Vec<(u64, u64)> = rows.iter()
2968            .map(|r| (r["a"].as_u64().unwrap(), r["b"].as_u64().unwrap()))
2969            .collect();
2970        assert_eq!(got, vec![(2, 1), (2, 2), (1, 1), (1, 2)]);
2971    }
2972
2973    /// The headline pipeline-order bug. In SQL, LIMIT applies to the RESULT.
2974    /// The old order was ORDER BY -> LIMIT -> GROUP BY, so LIMIT truncated the
2975    /// INPUT and the aggregate was computed over a fraction of the rows —
2976    /// reporting counts that summed to the limit instead of the true total.
2977    #[test]
2978    fn limit_applies_to_grouped_rows_not_to_the_input() {
2979        let dir = tempdir().unwrap();
2980        let db = Db::open(dir.path(), None).unwrap();
2981        for i in 0..12 {
2982            // Hoisted: json! cannot parse an indexing expression inline.
2983            let status = ["open", "closed", "void"][i % 3];
2984            db.put("t", &i.to_string(),
2985                serde_json::json!({"status": status, "fee": i}),
2986                vec![], None, None).unwrap();
2987        }
2988        let (all, _) = query(&db, "FROM t GROUP BY status COUNT").unwrap();
2989        assert_eq!(all.len(), 3);
2990        let total: u64 = all.iter().filter_map(|r| r["count"].as_u64()).sum();
2991        assert_eq!(total, 12, "every input row must be counted");
2992
2993        // LIMIT 2 must return 2 GROUPS, each with its full count — not two
2994        // input rows regrouped.
2995        let (limited, _) = query(&db, "FROM t GROUP BY status COUNT LIMIT 2").unwrap();
2996        assert_eq!(limited.len(), 2, "LIMIT caps the number of groups");
2997        for r in &limited {
2998            assert_eq!(r["count"], json!(4),
2999                       "each group keeps its true count, got {:?}", r);
3000        }
3001    }
3002
3003    /// The second pipeline-order bug: ORDER BY ran before grouping, so it
3004    /// sorted the raw documents on a field that only exists AFTER grouping
3005    /// (`count`, `sum_fee`) and the grouped output came back unordered. The
3006    /// clause was silently inert.
3007    #[test]
3008    fn order_by_sorts_the_grouped_rows() {
3009        let dir = tempdir().unwrap();
3010        let db = Db::open(dir.path(), None).unwrap();
3011        // Deliberately uneven: 1 x "a", 3 x "b", 2 x "c".
3012        for (i, s) in ["a", "b", "b", "b", "c", "c"].iter().enumerate() {
3013            db.put("t", &i.to_string(),
3014                serde_json::json!({"g": s, "n": i}), vec![], None, None).unwrap();
3015        }
3016        let (rows, _) = query(&db, "FROM t GROUP BY g COUNT ORDER BY count DESC").unwrap();
3017        let got: Vec<(String, u64)> = rows.iter()
3018            .map(|r| (r["g"].as_str().unwrap().to_string(), r["count"].as_u64().unwrap()))
3019            .collect();
3020        assert_eq!(got, vec![("b".into(), 3), ("c".into(), 2), ("a".into(), 1)]);
3021
3022        // And the group key itself is sortable.
3023        let (by_key, _) = query(&db, "FROM t GROUP BY g COUNT ORDER BY g DESC").unwrap();
3024        let keys: Vec<&str> = by_key.iter().map(|r| r["g"].as_str().unwrap()).collect();
3025        assert_eq!(keys, vec!["c", "b", "a"]);
3026    }
3027
3028    #[test]
3029    fn order_by_an_aggregate_key() {
3030        let (_tmp, db) = setup_items();
3031        let (rows, _) = query(
3032            &db, "FROM items GROUP BY cat SUM price ORDER BY sum_price DESC").unwrap();
3033        let cats: Vec<&str> = rows.iter().map(|r| r["cat"].as_str().unwrap()).collect();
3034        assert_eq!(cats, vec!["y", "x"], "y sums to 60, x to 15");
3035    }
3036
3037    #[test]
3038    fn offset_and_limit_page_grouped_rows() {
3039        let dir = tempdir().unwrap();
3040        let db = Db::open(dir.path(), None).unwrap();
3041        for i in 0..9 {
3042            db.put("t", &i.to_string(),
3043                serde_json::json!({"g": format!("g{}", i % 3)}), vec![], None, None).unwrap();
3044        }
3045        let (page, _) = query(
3046            &db, "FROM t GROUP BY g COUNT ORDER BY g LIMIT 1 OFFSET 1").unwrap();
3047        assert_eq!(page.len(), 1);
3048        assert_eq!(page[0]["g"], "g1");
3049    }
3050
3051    // ── HAVING ──────────────────────────────────────────────────────────────
3052
3053    #[test]
3054    fn having_filters_groups_by_count() {
3055        let dir = tempdir().unwrap();
3056        let db = Db::open(dir.path(), None).unwrap();
3057        for (i, s) in ["a", "b", "b", "b", "c", "c"].iter().enumerate() {
3058            db.put("t", &i.to_string(),
3059                serde_json::json!({"g": s, "n": i}), vec![], None, None).unwrap();
3060        }
3061        let (rows, _) = query(&db, "FROM t GROUP BY g COUNT HAVING count > 1").unwrap();
3062        let mut keys: Vec<&str> = rows.iter().map(|r| r["g"].as_str().unwrap()).collect();
3063        keys.sort();
3064        assert_eq!(keys, vec!["b", "c"], "the single-row group `a` is filtered out");
3065    }
3066
3067    #[test]
3068    fn having_filters_on_the_aggregate_value() {
3069        let (_tmp, db) = setup_items();
3070        // x sums to 15, y to 60.
3071        let (rows, _) = query(
3072            &db, "FROM items GROUP BY cat SUM price HAVING sum_price > 20").unwrap();
3073        assert_eq!(rows.len(), 1);
3074        assert_eq!(rows[0]["cat"], "y");
3075    }
3076
3077    /// HAVING gets the full predicate surface, because it runs through the
3078    /// same evaluator as WHERE rather than a second copy.
3079    #[test]
3080    fn having_supports_the_whole_predicate_surface() {
3081        let (_tmp, db) = setup_items();
3082        let (in_, _) = query(
3083            &db, r#"FROM items GROUP BY cat COUNT HAVING cat IN ("x")"#).unwrap();
3084        assert_eq!(in_.len(), 1);
3085        assert_eq!(in_[0]["cat"], "x");
3086
3087        let (btw, _) = query(
3088            &db, "FROM items GROUP BY cat SUM price HAVING sum_price BETWEEN 10 AND 20").unwrap();
3089        assert_eq!(btw.len(), 1);
3090        assert_eq!(btw[0]["cat"], "x");
3091
3092        let (like, _) = query(
3093            &db, r#"FROM items GROUP BY cat COUNT HAVING cat LIKE "y""#).unwrap();
3094        assert_eq!(like.len(), 1);
3095
3096        let (or_, _) = query(
3097            &db, "FROM items GROUP BY cat SUM price HAVING sum_price < 20 OR count = 3").unwrap();
3098        assert_eq!(or_.len(), 2);
3099    }
3100
3101    /// WHERE filters input rows, HAVING filters groups. Confusing them gives
3102    /// different answers, so the distinction must hold.
3103    #[test]
3104    fn where_and_having_are_different_stages() {
3105        let (_tmp, db) = setup_items();
3106        // WHERE drops rows BEFORE grouping, shrinking the sums.
3107        let (w, _) = query(
3108            &db, "FROM items WHERE price > 10 GROUP BY cat SUM price").unwrap();
3109        let x = w.iter().find(|r| r["cat"] == "x");
3110        assert!(x.is_none(), "x's rows (0,5,10) are all filtered out by WHERE");
3111
3112        // HAVING keeps every row in the aggregate and filters the RESULT.
3113        let (h, _) = query(
3114            &db, "FROM items GROUP BY cat SUM price HAVING sum_price > 10").unwrap();
3115        assert_eq!(h.len(), 2, "both groups sum above 10 when nothing is pre-filtered");
3116    }
3117
3118    #[test]
3119    fn having_without_an_aggregate_is_an_error() {
3120        let (_tmp, db) = setup();
3121        // HAVING is meaningless without grouping, and silently treating it as
3122        // a second WHERE would be exactly the kind of reinterpretation this
3123        // parser no longer does.
3124        assert!(query(&db, "FROM blocks HAVING height > 3").is_err());
3125    }
3126
3127    // ── Bare aggregates, no GROUP BY ────────────────────────────────────────
3128
3129    /// `FROM t COUNT` — "how many rows match?" without fetching them. The
3130    /// July engine note recorded `SELECT COUNT(*)` returning `[]` silently;
3131    /// this is the capability that was missing behind that silence.
3132    #[test]
3133    fn bare_count_returns_one_row() {
3134        let (_tmp, db) = setup();
3135        let (rows, _) = query(&db, "FROM blocks COUNT").unwrap();
3136        assert_eq!(rows.len(), 1);
3137        assert_eq!(rows[0]["count"], json!(5));
3138        assert_eq!(rows[0]["value"], json!(5));
3139    }
3140
3141    #[test]
3142    fn bare_count_respects_the_filter() {
3143        let (_tmp, db) = setup();
3144        let (rows, _) = query(&db, "FROM blocks WHERE height > 3 COUNT").unwrap();
3145        assert_eq!(rows[0]["count"], json!(2));
3146    }
3147
3148    #[test]
3149    fn bare_sum_avg_min_max() {
3150        let (_tmp, db) = setup();
3151        // heights 1..=5, n_tx = h*2 -> 2,4,6,8,10
3152        let (s, _) = query(&db, "FROM blocks SUM n_tx").unwrap();
3153        assert_eq!(s[0]["sum_n_tx"], json!(30), "integer inputs give an integer sum");
3154        let (a, _) = query(&db, "FROM blocks AVG n_tx").unwrap();
3155        assert_eq!(a[0]["avg_n_tx"], json!(6.0));
3156        let (mn, _) = query(&db, "FROM blocks MIN n_tx").unwrap();
3157        assert_eq!(mn[0]["min_n_tx"], json!(2));
3158        let (mx, _) = query(&db, "FROM blocks MAX n_tx").unwrap();
3159        assert_eq!(mx[0]["max_n_tx"], json!(10));
3160    }
3161
3162    /// Integer inputs must produce integer aggregates.
3163    ///
3164    /// Aggregating exclusively in f64 was a type divergence from the Python
3165    /// reference (which returns `66`, not `66.0`) AND a precision bug: f64
3166    /// cannot represent integers above 2^53 exactly, so a SUM over satoshi
3167    /// amounts or block heights silently rounded. This engine stores exactly
3168    /// that kind of number.
3169    #[test]
3170    fn integer_aggregates_stay_integers_and_keep_full_precision() {
3171        let dir = tempdir().unwrap();
3172        let db = Db::open(dir.path(), None).unwrap();
3173        // Beyond 2^53 (9_007_199_254_740_992), where f64 starts skipping
3174        // integers. Their true sum ends in ...9, which a f64 round-trip loses.
3175        let big: [i64; 3] = [9_007_199_254_740_993, 9_007_199_254_740_995, 1];
3176        for (i, v) in big.iter().enumerate() {
3177            db.put("t", &i.to_string(), serde_json::json!({"v": v}),
3178                   vec![], None, None).unwrap();
3179        }
3180        let (s, _) = query(&db, "FROM t SUM v").unwrap();
3181        assert_eq!(s[0]["sum_v"], json!(18_014_398_509_481_989i64),
3182                   "exact i64 sum, not a rounded f64");
3183        assert!(s[0]["sum_v"].is_i64(), "must serialise as an integer");
3184
3185        let (mx, _) = query(&db, "FROM t MAX v").unwrap();
3186        assert_eq!(mx[0]["max_v"], json!(9_007_199_254_740_995i64));
3187        let (mn, _) = query(&db, "FROM t MIN v").unwrap();
3188        assert_eq!(mn[0]["min_v"], json!(1));
3189    }
3190
3191    /// A float anywhere in the column makes the whole aggregate fractional,
3192    /// which is what Python's arithmetic does too.
3193    #[test]
3194    fn a_single_float_makes_the_aggregate_fractional() {
3195        let dir = tempdir().unwrap();
3196        let db = Db::open(dir.path(), None).unwrap();
3197        db.put("t", "1", serde_json::json!({"v": 1}), vec![], None, None).unwrap();
3198        db.put("t", "2", serde_json::json!({"v": 2.5}), vec![], None, None).unwrap();
3199        let (s, _) = query(&db, "FROM t SUM v").unwrap();
3200        assert_eq!(s[0]["sum_v"], json!(3.5));
3201        // AVG is true division, so it is fractional even over pure integers.
3202        let (a, _) = query(&db, "FROM t AVG v").unwrap();
3203        assert_eq!(a[0]["avg_v"], json!(1.75));
3204    }
3205
3206    /// A JSON bool is not a number, matching Python's explicit
3207    /// `not isinstance(x, bool)` guard.
3208    #[test]
3209    fn booleans_are_not_aggregated_as_numbers() {
3210        let dir = tempdir().unwrap();
3211        let db = Db::open(dir.path(), None).unwrap();
3212        db.put("t", "1", serde_json::json!({"v": true}), vec![], None, None).unwrap();
3213        db.put("t", "2", serde_json::json!({"v": 5}), vec![], None, None).unwrap();
3214        let (s, _) = query(&db, "FROM t SUM v").unwrap();
3215        assert_eq!(s[0]["sum_v"], json!(5), "the bool contributes nothing");
3216        assert_eq!(s[0]["count"], json!(2), "but it still counts toward the group");
3217    }
3218
3219    /// COUNT over an empty result is 0, not "no rows". A caller asking "how
3220    /// many?" must get a number.
3221    #[test]
3222    fn bare_count_of_nothing_is_zero_not_empty() {
3223        let (_tmp, db) = setup();
3224        let (rows, count) = query(&db, "FROM blocks WHERE height > 999 COUNT").unwrap();
3225        assert_eq!(count, 1, "still exactly one row");
3226        assert_eq!(rows[0]["count"], json!(0));
3227
3228        // A GROUPED aggregate over zero rows correctly has no groups.
3229        let (g, _) = query(&db, "FROM blocks WHERE height > 999 GROUP BY height COUNT").unwrap();
3230        assert!(g.is_empty());
3231    }
3232
3233    #[test]
3234    fn bare_aggregate_over_an_empty_collection() {
3235        let (_tmp, db) = setup();
3236        let (rows, _) = query(&db, "FROM nonexistent COUNT").unwrap();
3237        assert_eq!(rows[0]["count"], json!(0));
3238        let (s, _) = query(&db, "FROM nonexistent SUM n_tx").unwrap();
3239        assert_eq!(s[0]["sum_n_tx"], Value::Null, "sum of nothing is null, not 0");
3240    }
3241
3242    #[test]
3243    fn bare_aggregate_carries_no_group_key() {
3244        let (_tmp, db) = setup();
3245        let (rows, _) = query(&db, "FROM blocks COUNT").unwrap();
3246        if let Value::Object(m) = &rows[0] {
3247            let mut keys: Vec<&String> = m.keys().collect();
3248            keys.sort();
3249            assert_eq!(keys, vec!["count", "value"]);
3250        } else {
3251            panic!("expected an object");
3252        }
3253    }
3254
3255    /// A document field whose name collides with a reserved word must be
3256    /// addressable. The lexer uppercases keywords for matching, and field
3257    /// positions accept a keyword as a field name — but they used the
3258    /// UPPERCASED text, so `WHERE count > 1` searched the document for "COUNT"
3259    /// and matched nothing. Silent, and it hit real field names: count, min,
3260    /// max, sum, avg, value, search, group, order, limit, offset, trace.
3261    #[test]
3262    fn a_field_named_like_a_keyword_is_still_addressable() {
3263        let dir = tempdir().unwrap();
3264        let db = Db::open(dir.path(), None).unwrap();
3265        db.put("t", "1", serde_json::json!({
3266            "count": 5, "min": 1, "max": 9, "sum": 3, "avg": 2,
3267            "value": "keep", "limit": 7, "offset": 8, "group": "g1", "search": "s",
3268        }), vec![], None, None).unwrap();
3269        db.put("t", "2", serde_json::json!({
3270            "count": 1, "min": 0, "max": 2, "sum": 0, "avg": 0,
3271            "value": "drop", "limit": 0, "offset": 0, "group": "g2", "search": "t",
3272        }), vec![], None, None).unwrap();
3273
3274        for (nql, want) in [
3275            ("FROM t WHERE count > 3", "1"),
3276            ("FROM t WHERE min = 1", "1"),
3277            ("FROM t WHERE max >= 9", "1"),
3278            ("FROM t WHERE sum = 3", "1"),
3279            ("FROM t WHERE avg = 2", "1"),
3280            (r#"FROM t WHERE value = "keep""#, "1"),
3281            ("FROM t WHERE limit = 7", "1"),
3282            ("FROM t WHERE offset = 8", "1"),
3283            (r#"FROM t WHERE group = "g1""#, "1"),
3284        ] {
3285            let (rows, _) = query(&db, nql).unwrap();
3286            assert_eq!(rows.len(), 1, "`{}` matched {} rows", nql, rows.len());
3287            assert_eq!(rows[0]["_id"], want, "`{}`", nql);
3288        }
3289
3290        // Sorting and grouping on such a field too.
3291        let (ord, _) = query(&db, "FROM t ORDER BY count DESC").unwrap();
3292        assert_eq!(ord[0]["_id"], "1");
3293        let (grp, _) = query(&db, "FROM t GROUP BY group COUNT").unwrap();
3294        assert_eq!(grp.len(), 2);
3295        let keys: Vec<&str> = grp.iter().filter_map(|r| r["group"].as_str()).collect();
3296        assert!(keys.contains(&"g1") && keys.contains(&"g2"), "{:?}", grp);
3297    }
3298
3299    /// The raw spelling is preserved, so a mixed-case field name round-trips
3300    /// while the keyword it collides with still matches case-insensitively.
3301    #[test]
3302    fn keyword_matching_stays_case_insensitive() {
3303        let dir = tempdir().unwrap();
3304        let db = Db::open(dir.path(), None).unwrap();
3305        db.put("t", "1", serde_json::json!({"Count": 5, "n": 1}),
3306               vec![], None, None).unwrap();
3307        // Field spelled `Count`, clause keywords in lower case.
3308        let (rows, _) = query(&db, "from t where Count = 5 order by n").unwrap();
3309        assert_eq!(rows.len(), 1);
3310        // And a differently-cased field name does NOT collide with it.
3311        let (miss, _) = query(&db, "FROM t WHERE count = 5").unwrap();
3312        assert!(miss.is_empty(), "`count` and `Count` are distinct field names");
3313    }
3314
3315    #[test]
3316    fn two_aggregates_is_an_error() {
3317        let (_tmp, db) = setup();
3318        assert!(query(&db, "FROM blocks COUNT SUM n_tx").is_err());
3319        assert!(query(&db, "FROM blocks GROUP BY height COUNT SUM n_tx").is_err());
3320    }
3321
3322    #[test]
3323    fn bare_aggregate_with_having() {
3324        let (_tmp, db) = setup();
3325        let (keep, _) = query(&db, "FROM blocks COUNT HAVING count > 3").unwrap();
3326        assert_eq!(keep.len(), 1);
3327        let (drop, _) = query(&db, "FROM blocks COUNT HAVING count > 99").unwrap();
3328        assert!(drop.is_empty());
3329    }
3330
3331    // ── GROUP BY parity with the Python reference (query.py + engine.py) ────
3332
3333    /// Fixture mirroring tests/test_v050.py::test_group_by_min_max exactly:
3334    /// six items, cat x for 0..2 and y for 3..5, price = i * 5.
3335    fn setup_items() -> (tempfile::TempDir, Db) {
3336        let dir = tempdir().unwrap();
3337        let db = Db::open(dir.path(), None).unwrap();
3338        for i in 0..6 {
3339            db.put("items", &i.to_string(),
3340                serde_json::json!({"cat": if i < 3 {"x"} else {"y"}, "price": i * 5}),
3341                vec![], None, None).unwrap();
3342        }
3343        (dir, db)
3344    }
3345
3346    fn group(rows: &[Value], field: &str, key: &str) -> Value {
3347        rows.iter()
3348            .find(|r| r[field] == Value::String(key.to_string()))
3349            .unwrap_or_else(|| panic!("no group {:?} in {:?}", key, rows))
3350            .clone()
3351    }
3352
3353    /// The aggregate must read the TARGET field. Before 3.3.0 the executor
3354    /// aggregated the GROUP BY field itself and the target was silently
3355    /// dropped by the unknown-token skip, so `MAX price` returned the max of
3356    /// `cat` — a non-numeric value coerced to 1.0, making every group answer
3357    /// 1. Python returns x:0 and y:25 for MIN/MAX respectively.
3358    #[test]
3359    fn group_by_aggregates_the_target_field_not_the_group_field() {
3360        let (_tmp, db) = setup_items();
3361
3362        let (mins, _) = query(&db, "FROM items GROUP BY cat MIN price").unwrap();
3363        assert_eq!(group(&mins, "cat", "x")["min_price"], json!(0));
3364        assert_eq!(group(&mins, "cat", "y")["min_price"], json!(15));
3365
3366        let (maxs, _) = query(&db, "FROM items GROUP BY cat MAX price").unwrap();
3367        assert_eq!(group(&maxs, "cat", "y")["max_price"], json!(25));
3368        assert_eq!(group(&maxs, "cat", "x")["max_price"], json!(10));
3369
3370        let (sums, _) = query(&db, "FROM items GROUP BY cat SUM price").unwrap();
3371        assert_eq!(group(&sums, "cat", "x")["sum_price"], json!(15));  // 0+5+10
3372        assert_eq!(group(&sums, "cat", "y")["sum_price"], json!(60));  // 15+20+25
3373
3374        let (avgs, _) = query(&db, "FROM items GROUP BY cat AVG price").unwrap();
3375        assert_eq!(group(&avgs, "cat", "x")["avg_price"], json!(5.0));
3376        assert_eq!(group(&avgs, "cat", "y")["avg_price"], json!(20.0));
3377    }
3378
3379    /// An aggregate over a `_`-prefixed metadata field must see it.
3380    ///
3381    /// `_seq` lives on the node, not in its data payload, and the aggregator
3382    /// read the payload directly — so `MAX _seq` answered NULL while
3383    /// `SELECT _seq` listed the values and `WHERE _seq > 5` filtered on them.
3384    /// It was also a live divergence: the Python engine builds its groups from
3385    /// projected dicts that already carry `_seq`, and answers correctly.
3386    ///
3387    /// "What is the newest sequence?" is the question replication and time
3388    /// travel are built on, so a confident null there is the worst shape of
3389    /// wrong answer this engine can give.
3390    #[test]
3391    fn aggregates_see_node_metadata_not_only_the_payload() {
3392        let (_tmp, db) = setup_items();
3393        let (all, _) = query(&db, "FROM items").unwrap();
3394        let want = all.iter().filter_map(|r| r.get("_seq")?.as_i64()).max().unwrap();
3395
3396        let (rows, _) = query(&db, "FROM items MAX _seq").unwrap();
3397        assert_eq!(rows[0]["max__seq"], json!(want),
3398                   "MAX _seq must equal the highest sequence in the result");
3399        assert_ne!(rows[0]["max__seq"], Value::Null, "a null here is a silent wrong answer");
3400
3401        let (rows, _) = query(&db, "FROM items MIN _seq").unwrap();
3402        assert_eq!(rows[0]["min__seq"], json!(
3403            all.iter().filter_map(|r| r.get("_seq")?.as_i64()).min().unwrap()));
3404
3405        // Grouping by a metadata field works through the same resolver.
3406        let (rows, _) = query(&db, "FROM items GROUP BY _seq COUNT").unwrap();
3407        assert_eq!(rows.len(), all.len(), "one group per distinct sequence");
3408        assert!(rows.iter().all(|r| r["_seq"] != Value::Null),
3409                "the group key must be the sequence, not null");
3410    }
3411
3412    /// Output key parity: Python's engine.py emits `<agg>_<field>` and a
3413    /// `count`. This engine additionally keeps `value` as the alias it has
3414    /// always emitted, so existing callers keep working.
3415    #[test]
3416    fn group_by_emits_python_parity_keys_and_the_value_alias() {
3417        let (_tmp, db) = setup_items();
3418        let (rows, _) = query(&db, "FROM items GROUP BY cat SUM price").unwrap();
3419        let x = group(&rows, "cat", "x");
3420        assert_eq!(x["sum_price"], json!(15), "python-parity key");
3421        assert_eq!(x["value"], json!(15), "back-compat alias must agree");
3422        assert_eq!(x["count"], json!(3), "count is the group size");
3423    }
3424
3425    /// `count` is the group size; the aggregate only sees numeric targets.
3426    /// A group of 3 where one row has a non-numeric price must still report
3427    /// count=3 while averaging over 2 — matching Python's isinstance filter.
3428    #[test]
3429    fn count_is_group_size_while_aggregate_skips_non_numeric() {
3430        let dir = tempdir().unwrap();
3431        let db = Db::open(dir.path(), None).unwrap();
3432        db.put("t", "1", serde_json::json!({"g": "a", "n": 10}), vec![], None, None).unwrap();
3433        db.put("t", "2", serde_json::json!({"g": "a", "n": 20}), vec![], None, None).unwrap();
3434        db.put("t", "3", serde_json::json!({"g": "a", "n": "N/A"}), vec![], None, None).unwrap();
3435
3436        let (rows, _) = query(&db, "FROM t GROUP BY g AVG n").unwrap();
3437        let a = group(&rows, "g", "a");
3438        assert_eq!(a["count"], json!(3), "every row counts toward the group");
3439        assert_eq!(a["avg_n"], json!(15.0), "only the two numeric rows average");
3440    }
3441
3442    /// An aggregate with no numeric input is null, not 0 and not infinity.
3443    #[test]
3444    fn empty_aggregate_input_is_null() {
3445        let dir = tempdir().unwrap();
3446        let db = Db::open(dir.path(), None).unwrap();
3447        db.put("t", "1", serde_json::json!({"g": "a", "n": "x"}), vec![], None, None).unwrap();
3448        let (rows, _) = query(&db, "FROM t GROUP BY g MIN n").unwrap();
3449        assert_eq!(rows[0]["min_n"], Value::Null);
3450        assert_eq!(rows[0]["count"], json!(1));
3451    }
3452
3453    /// Python makes the aggregate keyword optional — `GROUP BY field` alone
3454    /// yields counts. Rust used to reject it as a parse error.
3455    #[test]
3456    fn bare_group_by_without_an_aggregate_counts() {
3457        let (_tmp, db) = setup_items();
3458        let (rows, _) = query(&db, "FROM items GROUP BY cat").unwrap();
3459        assert_eq!(rows.len(), 2);
3460        assert_eq!(group(&rows, "cat", "x")["count"], json!(3));
3461        assert_eq!(group(&rows, "cat", "y")["count"], json!(3));
3462    }
3463
3464    /// SUM/AVG/MIN/MAX require a target field, as in Python.
3465    #[test]
3466    fn aggregate_without_a_target_field_is_an_error() {
3467        let (_tmp, db) = setup_items();
3468        for bad in [
3469            "FROM items GROUP BY cat SUM",
3470            "FROM items GROUP BY cat AVG",
3471            "FROM items GROUP BY cat MIN",
3472        ] {
3473            assert!(query(&db, bad).is_err(), "`{}` must be rejected", bad);
3474        }
3475    }
3476
3477    /// Group output order is first-seen, so repeated runs agree. HashMap
3478    /// iteration order previously made this nondeterministic.
3479    #[test]
3480    fn group_order_is_stable_across_runs() {
3481        let (_tmp, db) = setup_items();
3482        let first = query(&db, "FROM items GROUP BY cat SUM price").unwrap().0;
3483        for _ in 0..8 {
3484            let again = query(&db, "FROM items GROUP BY cat SUM price").unwrap().0;
3485            assert_eq!(first, again);
3486        }
3487    }
3488
3489    /// GROUP BY composes with the new predicate surface.
3490    #[test]
3491    fn group_by_after_an_in_predicate() {
3492        let (_tmp, db) = setup_items();
3493        let (rows, _) = query(
3494            &db, "FROM items WHERE price IN (0, 5, 25) GROUP BY cat SUM price").unwrap();
3495        assert_eq!(group(&rows, "cat", "x")["sum_price"], json!(5));
3496        assert_eq!(group(&rows, "cat", "y")["sum_price"], json!(25));
3497    }
3498
3499    #[test]
3500    fn search() {
3501        let (_tmp, db) = setup();
3502        let (rows, _) = query(&db, r#"FROM blocks SEARCH "0003""#).unwrap();
3503        assert_eq!(rows.len(), 1);
3504    }
3505
3506    #[test]
3507    fn as_of() {
3508        let dir = tempdir().unwrap();
3509        let db = Db::open(dir.path(), None).unwrap();
3510        let v1 = db.put("docs", "x", serde_json::json!({"v": 1}), vec![], None, None).unwrap();
3511        db.put("docs", "x", serde_json::json!({"v": 2}), vec![], None, None).unwrap();
3512        let (rows, _) = query(&db, &format!("FROM docs AS OF {}", v1.seq)).unwrap();
3513        assert_eq!(rows[0]["v"], 1);
3514    }
3515
3516    #[test]
3517    fn valid_as_of() {
3518        let dir = tempdir().unwrap();
3519        let db = Db::open(dir.path(), None).unwrap();
3520        db.put("events", "e1", serde_json::json!({"type": "a"}), vec![],
3521               Some("2025-01-01".to_string()), Some("2025-06-01".to_string())).unwrap();
3522        db.put("events", "e2", serde_json::json!({"type": "b"}), vec![],
3523               Some("2026-01-01".to_string()), None).unwrap();
3524        let (rows, _) = query(&db, r#"FROM events VALID AS OF "2025-03-01""#).unwrap();
3525        assert_eq!(rows.len(), 1);
3526        assert_eq!(rows[0]["type"], "a");
3527    }
3528
3529    // ── String-literal escaping ──────────────────────────────────────────────
3530
3531    #[test]
3532    fn escaped_quote_matches_a_value_containing_a_quote() {
3533        let dir = tempdir().unwrap();
3534        let db = Db::open(dir.path(), None).unwrap();
3535        db.put("m", "q", serde_json::json!({ "name": "say \"hi\"" }), vec![], None, None)
3536            .unwrap();
3537        db.put("m", "p", serde_json::json!({ "name": "plain" }), vec![], None, None).unwrap();
3538
3539        // \" inside the literal is a literal quote; the string does not end there.
3540        let (rows, count) = query(&db, r#"FROM m WHERE name = "say \"hi\"""#).unwrap();
3541        assert_eq!(count, 1, "the escaped-quote literal matches exactly one row");
3542        assert_eq!(rows[0]["_id"], "q");
3543    }
3544
3545    #[test]
3546    fn raw_backslash_still_matches_literally() {
3547        // REGRESSION GUARD: a lone backslash stays literal, so pre-existing
3548        // backslash queries (Windows paths etc.) keep matching. This is the
3549        // property that makes the \" addition non-breaking.
3550        let dir = tempdir().unwrap();
3551        let db = Db::open(dir.path(), None).unwrap();
3552        db.put("m", "b", serde_json::json!({ "p": "back\\slash" }), vec![], None, None).unwrap();
3553
3554        let (rows, count) = query(&db, r#"FROM m WHERE p = "back\slash""#).unwrap();
3555        assert_eq!(count, 1, "a raw backslash literal matches as before");
3556        assert_eq!(rows[0]["_id"], "b");
3557    }
3558
3559    #[test]
3560    fn a_quote_can_no_longer_inject_trailing_clauses() {
3561        // The security motivation: previously a value of `x" LIMIT 1` would
3562        // terminate the literal and inject `LIMIT 1`. With \" the caller can
3563        // escape the quote so it stays part of the value and matches nothing
3564        // rogue. Here the escaped form matches the literal value verbatim.
3565        let dir = tempdir().unwrap();
3566        let db = Db::open(dir.path(), None).unwrap();
3567        db.put("m", "x", serde_json::json!({ "v": "a\"b" }), vec![], None, None).unwrap();
3568        let (rows, count) = query(&db, r#"FROM m WHERE v = "a\"b""#).unwrap();
3569        assert_eq!(count, 1);
3570        assert_eq!(rows[0]["_id"], "x");
3571    }
3572}
3573
3574#[cfg(test)]
3575mod tests_traverse {
3576    use super::*;
3577    use tempfile::tempdir;
3578    use crate::db::Db;
3579
3580    #[test]
3581    fn traverse_one_hop() {
3582        let db = Db::in_memory();
3583        db.put("driver", "d1", serde_json::json!({"name": "Bob"}),   vec![], None, None).unwrap();
3584        db.put("driver", "d2", serde_json::json!({"name": "Carol"}), vec![], None, None).unwrap();
3585        db.put("trip",   "t1", serde_json::json!({"status": "req"}), vec![], None, None).unwrap();
3586        db.put("trip",   "t2", serde_json::json!({"status": "ok"}),  vec![], None, None).unwrap();
3587
3588        db.link("driver:d1", "handles", "trip:t1").unwrap();
3589        db.link("driver:d1", "handles", "trip:t2").unwrap();
3590
3591        let (rows, count) = query(&db, r#"FROM driver WHERE _id = "d1" TRAVERSE handles"#).unwrap();
3592        assert_eq!(count, 2);
3593        let ids: std::collections::HashSet<&str> = rows.iter()
3594            .filter_map(|r| r["_id"].as_str())
3595            .collect();
3596        assert!(ids.contains("t1") && ids.contains("t2"));
3597    }
3598
3599    #[test]
3600    fn traverse_returns_empty_when_no_links() {
3601        let db = Db::in_memory();
3602        db.put("driver", "d1", serde_json::json!({"name": "Bob"}), vec![], None, None).unwrap();
3603        let (rows, count) = query(&db, r#"FROM driver WHERE _id = "d1" TRAVERSE handles"#).unwrap();
3604        assert_eq!(count, 0);
3605        assert!(rows.is_empty());
3606    }
3607
3608    #[test]
3609    fn traverse_multi_source() {
3610        // When WHERE matches multiple rows, TRAVERSE unions all their neighbors
3611        let db = Db::in_memory();
3612        db.put("driver", "d1", serde_json::json!({"status": "active"}), vec![], None, None).unwrap();
3613        db.put("driver", "d2", serde_json::json!({"status": "active"}), vec![], None, None).unwrap();
3614        db.put("trip",   "t1", serde_json::json!({"n": 1}), vec![], None, None).unwrap();
3615        db.put("trip",   "t2", serde_json::json!({"n": 2}), vec![], None, None).unwrap();
3616        db.put("trip",   "t3", serde_json::json!({"n": 3}), vec![], None, None).unwrap();
3617
3618        db.link("driver:d1", "handles", "trip:t1").unwrap();
3619        db.link("driver:d1", "handles", "trip:t2").unwrap();
3620        db.link("driver:d2", "handles", "trip:t3").unwrap();
3621
3622        let (_rows, count) = query(&db, r#"FROM driver WHERE status = "active" TRAVERSE handles"#).unwrap();
3623        assert_eq!(count, 3);
3624    }
3625
3626    #[test]
3627    fn traverse_nql_keyword_case_insensitive() {
3628        // Parser normalises to uppercase — "traverse" and "TRAVERSE" both work
3629        let db = Db::in_memory();
3630        db.put("driver", "d1", serde_json::json!({}), vec![], None, None).unwrap();
3631        db.put("trip",   "t1", serde_json::json!({}), vec![], None, None).unwrap();
3632        db.link("driver:d1", "handles", "trip:t1").unwrap();
3633        // uppercase
3634        let (r1, c1) = query(&db, r#"FROM driver WHERE _id = "d1" TRAVERSE handles"#).unwrap();
3635        assert_eq!(c1, 1);
3636        // lowercase (lexer uppercases keywords)
3637        let (r2, c2) = query(&db, r#"FROM driver WHERE _id = "d1" traverse handles"#).unwrap();
3638        assert_eq!(c2, 1);
3639        assert_eq!(r1[0]["_id"], r2[0]["_id"]);
3640    }
3641
3642    #[test]
3643    fn traverse_durable() {
3644        let dir = tempdir().unwrap();
3645        {
3646            let db = Db::open(dir.path(), None).unwrap();
3647            db.put("driver", "d1", serde_json::json!({"name": "Bob"}),   vec![], None, None).unwrap();
3648            db.put("trip",   "t1", serde_json::json!({"status": "req"}), vec![], None, None).unwrap();
3649            db.link("driver:d1", "handles", "trip:t1").unwrap();
3650        }
3651        let db2 = Db::open(dir.path(), None).unwrap();
3652        db2.startup_ready.store(true, std::sync::atomic::Ordering::SeqCst);
3653        let (rows, count) = query(&db2, r#"FROM driver WHERE _id = "d1" TRAVERSE handles"#).unwrap();
3654        assert_eq!(count, 1);
3655        assert_eq!(rows[0]["_id"], "t1");
3656    }
3657}