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