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
1475fn matches_valid_as_of(node: &Node, date: &str) -> bool {
1476    // A node is valid at `date` if:
1477    //   valid_from is None OR valid_from <= date
1478    //   AND (valid_to is None OR valid_to > date)
1479    let from_ok = node.valid_from.as_deref().map(|f| f <= date).unwrap_or(true);
1480    let to_ok   = node.valid_to.as_deref().map(|t| t > date).unwrap_or(true);
1481    from_ok && to_ok
1482}
1483
1484fn node_contains_text(node: &Node, text: &str) -> bool {
1485    let s = node.data.to_string().to_lowercase();
1486    s.contains(&text.to_lowercase())
1487}
1488
1489/// A node as a flat query row: data fields at the top level plus the `_`-prefixed
1490/// metadata. Public so the HTTP single-row GET returns the SAME shape a query row
1491/// has — one definition, so the two surfaces cannot drift apart.
1492pub fn node_to_json(node: &Node) -> Value {
1493    let mut obj = if let Value::Object(m) = &node.data {
1494        m.clone()
1495    } else {
1496        serde_json::Map::new()
1497    };
1498    obj.insert("_id".to_string(),   Value::String(node.id.clone()));
1499    obj.insert("_hash".to_string(), Value::String(node.hash.clone()));
1500    obj.insert("_seq".to_string(),  json!(node.seq));
1501    obj.insert("_coll".to_string(), Value::String(node.coll.clone()));
1502    if let Some(ref vf) = node.valid_from {
1503        obj.insert("_valid_from".to_string(), Value::String(vf.clone()));
1504    }
1505    if let Some(ref vt) = node.valid_to {
1506        obj.insert("_valid_to".to_string(), Value::String(vt.clone()));
1507    }
1508    if !node.caused_by.is_empty() {
1509        obj.insert("_caused_by".to_string(), Value::Array(
1510            node.caused_by.iter().map(|h| Value::String(h.clone())).collect()
1511        ));
1512    }
1513    Value::Object(obj)
1514}
1515
1516/// Execute a NQL query against the DAG database.
1517/// Parse NQL into a `Query` WITHOUT touching the database.
1518///
1519/// `execute` already does exactly this as its first step; exposing it separately
1520/// lets callers validate a query before deciding to run it. The natural-language
1521/// planner (`/v1/databases/:name/cast`) uses it to answer "is this runnable?"
1522/// without side effects — checking the text against the real grammar rather than
1523/// pattern-matching it, because the parser is the only authority on that.
1524pub fn parse(nql: &str) -> Result<Query> {
1525    let mut lexer = Lexer::new(nql);
1526    let toks = lexer.tokenize();
1527    let mut parser = Parser::new(toks);
1528    parser.parse()
1529}
1530
1531pub fn execute(db: &Db, nql: &str) -> Result<Vec<Value>> {
1532    // One parse path, shared with the public `parse()` above — so validation and
1533    // execution can never disagree about what is well-formed.
1534    let q = parse(nql)?;
1535
1536    // ── Candidate generation ──────────────────────────────────────────────────
1537
1538    // Fast path: single equality filter on _id with no AS OF.
1539    // Skip the O(n) collection scan — go straight to the id index (O(1) file read).
1540    // This turns `FROM coll WHERE _id = "x" LIMIT 1` from a full-table-scan into
1541    // a single file read, giving orders-of-magnitude speedup for point lookups.
1542    let id_eq_fast_path: Option<String> = if q.as_of.is_none() && q.trace.is_none() {
1543        q.where_.as_ref().and_then(id_point_lookup)
1544    } else { None };
1545
1546    let candidates: Vec<Node> = if let Some(ref target_id) = id_eq_fast_path {
1547        // O(1) direct id-index lookup — skip full collection scan entirely
1548        db.get(&q.coll, target_id).into_iter().collect()
1549    } else if let Some(seq_target) = q.as_of {
1550        // AS OF: return each doc's version at or before target seq.
1551        //
1552        // Over the live ids PLUS the deleted ones. Walking only `id_index`
1553        // meant a DELETED document was invisible at every sequence, including
1554        // sequences before the delete where it demonstrably existed — so
1555        // `AS OF` contradicted the promise that a delete is a tombstone rather
1556        // than an erasure. `get_as_of` reaches the chain through the graveyard
1557        // pointer, and returns nothing for a sequence at or after the
1558        // tombstone, where the document really is gone.
1559        db.list_ids_including_deleted(&q.coll).into_iter()
1560            .filter_map(|id| db.get_as_of(&q.coll, &id, seq_target))
1561            .collect()
1562    } else if let Some(plan) = q.where_.as_ref()
1563        // An indexed range or point-set scan, when a sorted index covers a
1564        // field the predicate constrains.
1565        //
1566        // Deliberately NOT attempted for AS OF: the sorted index holds current
1567        // versions only (a superseded hash is dropped on overwrite), so an
1568        // index scan would answer a historical query with present-day rows.
1569        // AS OF is handled by the branch above, which walks the id index and
1570        // resolves each document at the target seq.
1571        .filter(|_| q.as_of.is_none())
1572        .and_then(|p| choose_index_plan(db, &q.coll, p))
1573    {
1574        // The full predicate re-runs on these candidates below, so the plan
1575        // only has to be a superset — it can never make the answer wrong.
1576        let got = match &plan {
1577            IndexPlan::Range { field, low, high, low_incl, high_incl } => db.range_scan(
1578                &q.coll, field, low.as_ref(), high.as_ref(), *low_incl, *high_incl),
1579            IndexPlan::Values { field, values } => db.index_lookup(&q.coll, field, values),
1580        };
1581        match got {
1582            Some(nodes) => nodes,
1583            // The index vanished between planning and execution. Fall back
1584            // rather than answering from nothing.
1585            None => db.list(&q.coll),
1586        }
1587    } else if q.order_by.len() == 1 && q.aggregate.is_none() {
1588        // ORDER BY with optional sorted index — get candidates in order.
1589        //
1590        // Single key only: the sorted index is per-field, so a multi-key sort
1591        // cannot be served from it and falls through to the post-filter sort
1592        // below. Never used when aggregating either, because the sort then
1593        // applies to the GROUPED rows, which do not exist yet.
1594        //
1595        // Push LIMIT down into the index scan ONLY when nothing filters rows
1596        // after candidate generation. WHERE / SEARCH / VALID AS OF all run on
1597        // the candidate set below, so truncating to the top-k FIRST returns
1598        // incomplete results: `WHERE n_tx > 100 ORDER BY height LIMIT 10`
1599        // would fetch the 10 lowest blocks by height and then filter — losing
1600        // matches past the top-k window. The Python reference filters → sorts
1601        // → limits (engine.py execute()); this keeps the engines in agreement.
1602        let key = &q.order_by[0];
1603        let has_post_filters = q.where_.is_some()
1604            || q.search.is_some()
1605            || q.valid_as_of.is_some();
1606        let limit = if has_post_filters {
1607            9_999_999
1608        } else {
1609            // OFFSET is applied AFTER the sort, so the pushdown has to fetch
1610            // offset + limit rows and discard the prefix later. Fetching only
1611            // `limit` would return the first page for every page.
1612            match q.limit {
1613                Some(n) => n.saturating_add(q.offset.unwrap_or(0)),
1614                None => 9_999_999,
1615            }
1616        };
1617        if key.desc {
1618            db.order_by_desc(&q.coll, &key.field, limit)
1619        } else {
1620            db.order_by_asc(&q.coll, &key.field, limit)
1621        }
1622    } else if let (Some(n), true) = (q.limit, q.where_.is_none()
1623            && q.search.is_none() && q.trace.is_none()
1624            && q.traverse.is_none() && q.aggregate.is_none()
1625            && q.order_by.is_empty() && q.offset.is_none()
1626            && q.valid_as_of.is_none()) {
1627        // LIMIT-only fast path: no filters, no ordering, no trace.
1628        // Take only the first N IDs from the id-index and fetch those docs.
1629        // This makes `FROM coll LIMIT 1` O(N) not O(total) — critical for
1630        // the Studio "Preparing…" phase which samples every collection.
1631        db.id_index
1632            .list_ids(&q.coll)
1633            .into_iter()
1634            .take(n)
1635            .filter_map(|id| db.get(&q.coll, &id))
1636            .collect()
1637    } else {
1638        // Default: all docs in collection
1639        db.list(&q.coll)
1640    };
1641
1642    // ── WHERE filter ──────────────────────────────────────────────────────────
1643
1644    let mut rows: Vec<Node> = candidates.into_iter()
1645        .filter(|n| q.where_.as_ref().map(|p| eval_pred(n, p)).unwrap_or(true))
1646        .filter(|n| q.valid_as_of.as_deref()
1647                       .map(|d| matches_valid_as_of(n, d))
1648                       .unwrap_or(true))
1649        .filter(|n| q.search.as_deref()
1650                       .map(|t| node_contains_text(n, t))
1651                       .unwrap_or(true))
1652        .collect();
1653
1654    // ── TRACE ─────────────────────────────────────────────────────────────────
1655
1656    if let Some(ref _edge_type) = q.trace {
1657        let limit = q.limit.unwrap_or(1000);
1658        let mut traced: Vec<Node> = vec![];
1659        for root in &rows {
1660            let chain = db.trace(&root.hash, q.trace_rev, limit);
1661            traced.extend(chain);
1662        }
1663        rows = traced;
1664    }
1665
1666    // ── TRAVERSE rel — one-hop named-relation lookup ──────────────────────────
1667
1668    if let Some(ref rel) = q.traverse {
1669        let mut traversed: Vec<Node> = vec![];
1670        for root in &rows {
1671            let frm = format!("{}:{}", root.coll, root.id);
1672            let neighbors = db.neighbors(&frm, rel);
1673            traversed.extend(neighbors);
1674        }
1675        rows = traversed;
1676    }
1677
1678    // ── Aggregate → HAVING → ORDER BY → OFFSET → LIMIT ───────────────────────
1679    //
1680    // This is the SQL pipeline order, and getting it wrong was a live source
1681    // of silently-wrong answers. The old order was ORDER BY → LIMIT → GROUP BY,
1682    // which means:
1683    //
1684    //   `LIMIT 5 GROUP BY status COUNT` truncated the INPUT to five rows and
1685    //   then grouped them, so with twelve rows across three statuses the
1686    //   counts summed to 5 instead of 12. A confident wrong aggregate.
1687    //
1688    //   `ORDER BY count DESC GROUP BY status COUNT` sorted the raw documents
1689    //   on a field none of them carry (`count` only exists after grouping),
1690    //   so the grouped output came back in arbitrary order and the clause was
1691    //   silently inert.
1692    //
1693    // In SQL, LIMIT and ORDER BY apply to the RESULT. They now do here.
1694
1695    if let Some(ref spec) = q.aggregate {
1696        let mut out = aggregate_rows(&rows, spec);
1697
1698        // HAVING filters the aggregated rows, so it can test `count`,
1699        // `sum_fee` or the group key — none of which exist before this point.
1700        if let Some(ref pred) = q.having {
1701            out.retain(|row| eval_pred_json(row, pred));
1702        }
1703
1704        if !q.order_by.is_empty() {
1705            sort_by_keys(&mut out, &q.order_by,
1706                         |row, f| row.get(f).cloned().unwrap_or(Value::Null));
1707        } else if let Some(ref gf) = spec.group_field {
1708            // Deterministic default: groups sorted by key.
1709            //
1710            // NOT first-seen order. The Python reference draws candidates from
1711            // a `set`, so its input row order is arbitrary; a first-seen
1712            // ordering would differ between the two engines even though both
1713            // are internally consistent. Sorting by the key gives one answer
1714            // they can agree on, which the cross-engine parity suite pins.
1715            let gf = gf.clone();
1716            out.sort_by(|a, b| {
1717                as_text(&a.get(&gf).cloned().unwrap_or(Value::Null))
1718                    .cmp(&as_text(&b.get(&gf).cloned().unwrap_or(Value::Null)))
1719            });
1720        }
1721
1722        return Ok(paginate(out, q.offset, q.limit));
1723    }
1724
1725    if q.having.is_some() {
1726        bail!("HAVING requires an aggregate — add GROUP BY <field>, or use WHERE \
1727               to filter individual rows");
1728    }
1729
1730    // ── ORDER BY (post-filter sort if no sorted index was used) ──────────────
1731
1732    if !q.order_by.is_empty() {
1733        // The single-key sorted-index path above already returned candidates
1734        // in order, but only when nothing filtered them afterwards. Re-sort
1735        // whenever a filter ran, or whenever the sort has more than one key.
1736        let index_path_held = q.order_by.len() == 1
1737            && q.as_of.is_none()
1738            && q.where_.is_none()
1739            && q.search.is_none()
1740            && q.valid_as_of.is_none()
1741            && q.trace.is_none()
1742            && q.traverse.is_none();
1743        if !index_path_held {
1744            sort_by_keys(&mut rows, &q.order_by,
1745                         |n, f| field_value(n, f));
1746        }
1747    }
1748
1749    // ── OFFSET then LIMIT ────────────────────────────────────────────────────
1750
1751    let rows = paginate(rows, q.offset, q.limit);
1752
1753    // ── Serialize ─────────────────────────────────────────────────────────────
1754
1755    Ok(rows.into_iter().map(|n| node_to_json(&n)).collect())
1756}
1757
1758/// Parse and execute NQL, returning (rows, count).
1759pub fn query(db: &Db, nql: &str) -> Result<(Vec<Value>, usize)> {
1760    let rows = execute(db, nql)?;
1761    let count = rows.len();
1762    Ok((rows, count))
1763}
1764
1765/// Run a query's WHERE / ORDER BY / OFFSET / LIMIT against rows ALREADY IN
1766/// HAND, rather than against stored documents.
1767///
1768/// This is what makes `pg_catalog` and `information_schema` real queryable
1769/// tables instead of pattern-matched query strings. A catalogue row is
1770/// synthesised from the live database, never stored — but `psql` filters and
1771/// orders it with ordinary SQL, so it needs the ordinary predicate surface.
1772///
1773/// The alternative was to recognise psql's exact query text and answer it from
1774/// a fixed table. That breaks SILENTLY the moment psql changes its query, and
1775/// an empty table list is indistinguishable from "this database has no
1776/// tables" — the same class of confidently-wrong answer as everything else
1777/// this engine has had to fix. So the predicate engine is REUSED here rather
1778/// than a second, poorer copy being written: one `eval_pred_with`, one
1779/// `sort_by_keys`, one `paginate`, already tested.
1780///
1781/// Clauses that only mean something against the log — `AS OF`, `VALID AS OF`,
1782/// `TRACE`, `TRAVERSE`, `SEARCH`, and aggregates — are REFUSED by name. A
1783/// catalogue has no history and no causal edges; silently ignoring the clause
1784/// would answer a time-travel question with present-day rows.
1785pub fn query_rows(rows: Vec<Value>, nql: &str) -> Result<Vec<Value>> {
1786    let q = parse(nql)?;
1787
1788    for (unsupported, clause) in [
1789        (q.as_of.is_some(), "AS OF"),
1790        (q.valid_as_of.is_some(), "VALID AS OF"),
1791        (q.trace.is_some(), "TRACE"),
1792        (q.traverse.is_some(), "TRAVERSE"),
1793        (q.search.is_some(), "SEARCH"),
1794        (q.aggregate.is_some(), "an aggregate"),
1795        (q.having.is_some(), "HAVING"),
1796    ] {
1797        if unsupported {
1798            bail!("{} is not supported on the catalogue table {:?} — a catalogue \
1799                   is synthesised from the current database, so it has no history, \
1800                   no causal edges and nothing to aggregate. Query the collection \
1801                   itself for those", clause, q.coll);
1802        }
1803    }
1804
1805    let get = |row: &Value, field: &str| -> Value {
1806        row.get(field).cloned().unwrap_or(Value::Null)
1807    };
1808
1809    let mut kept: Vec<Value> = match &q.where_ {
1810        None => rows,
1811        Some(pred) => rows
1812            .into_iter()
1813            .filter(|r| eval_pred_with(&|f| get(r, f), pred))
1814            .collect(),
1815    };
1816
1817    if !q.order_by.is_empty() {
1818        sort_by_keys(&mut kept, &q.order_by, get);
1819    }
1820    Ok(paginate(kept, q.offset, q.limit))
1821}
1822
1823#[cfg(test)]
1824mod tests {
1825    use super::*;
1826    use tempfile::tempdir;
1827    use crate::db::Db;
1828
1829    // Returns (TempDir, Db) — the TempDir guard MUST be kept alive by the caller
1830    // (`let (_tmp, db) = setup();`). If it dropped here, its Drop would delete the
1831    // database directory out from under the live Db, and every objects.read()
1832    // (loose object files live on disk) would fail → queries return 0 rows.
1833    fn setup() -> (tempfile::TempDir, Db) {
1834        let dir = tempdir().unwrap();
1835        let db = Db::open(dir.path(), None).unwrap();
1836        db.create_sorted_index("blocks", "height");
1837        for h in 1u64..=5 {
1838            db.put("blocks", &h.to_string(),
1839                serde_json::json!({"height": h, "hash": format!("000{}", h), "n_tx": h * 2}),
1840                vec![], None, None).unwrap();
1841        }
1842        (dir, db)
1843    }
1844
1845    #[test]
1846    fn from_all() {
1847        let (_tmp, db) = setup();
1848        let (rows, count) = query(&db, "FROM blocks").unwrap();
1849        assert_eq!(count, 5);
1850        let _ = rows;
1851    }
1852
1853    #[test]
1854    fn where_eq() {
1855        let (_tmp, db) = setup();
1856        let (rows, count) = query(&db, r#"FROM blocks WHERE _id = "3""#).unwrap();
1857        assert_eq!(count, 1);
1858        assert_eq!(rows[0]["_id"], "3");
1859    }
1860
1861    #[test]
1862    fn order_by_limit() {
1863        let (_tmp, db) = setup();
1864        let (rows, count) = query(&db, "FROM blocks ORDER BY height ASC LIMIT 3").unwrap();
1865        assert_eq!(count, 3);
1866        assert_eq!(rows[0]["height"], 1);
1867        assert_eq!(rows[2]["height"], 3);
1868    }
1869
1870    #[test]
1871    fn order_by_desc() {
1872        let (_tmp, db) = setup();
1873        let (rows, _) = query(&db, "FROM blocks ORDER BY height DESC LIMIT 2").unwrap();
1874        assert_eq!(rows[0]["height"], 5);
1875    }
1876
1877    #[test]
1878    fn where_gt() {
1879        let (_tmp, db) = setup();
1880        let (rows, _) = query(&db, "FROM blocks WHERE height > 3").unwrap();
1881        assert_eq!(rows.len(), 2);
1882    }
1883
1884    /// Regression: WHERE + ORDER BY + LIMIT must not truncate candidates
1885    /// before the filter runs. setup() gives heights 1..=5 with n_tx = h*2;
1886    /// the predicate matches ONLY the two highest heights (4, 5). The old
1887    /// code passed LIMIT into the sorted-index top-k first: it fetched
1888    /// heights [1, 2], filtered on n_tx >= 8, and returned ZERO rows even
1889    /// though two matches exist. Python reference returns [4, 5].
1890    #[test]
1891    fn where_order_limit_does_not_truncate_before_filter() {
1892        let (_tmp, db) = setup();
1893        let (rows, count) =
1894            query(&db, "FROM blocks WHERE n_tx >= 8 ORDER BY height LIMIT 2").unwrap();
1895        assert_eq!(count, 2, "both matching rows must survive the limit");
1896        let heights: Vec<u64> = rows.iter()
1897            .filter_map(|r| r["height"].as_u64())
1898            .collect();
1899        assert_eq!(heights, vec![4, 5]);
1900        // And the same shape DESC — top match first.
1901        let (rows_d, _) =
1902            query(&db, "FROM blocks WHERE n_tx >= 8 ORDER BY height DESC LIMIT 1").unwrap();
1903        assert_eq!(rows_d.len(), 1);
1904        assert_eq!(rows_d[0]["height"], 5);
1905    }
1906
1907    // ── Predicate parity (3.3.0) ─────────────────────────────────────────────
1908    //
1909    // setup() gives blocks 1..=5 with height = h, hash = "000{h}",
1910    // n_tx = h * 2. Every test below asserts against that fixture.
1911
1912    /// A second fixture with string fields and a sparse column, for LIKE and
1913    /// IS NULL. `miner` is absent on one row on purpose.
1914    fn setup_text() -> (tempfile::TempDir, Db) {
1915        let dir = tempdir().unwrap();
1916        let db = Db::open(dir.path(), None).unwrap();
1917        let rows = [
1918            ("1", serde_json::json!({"status": "open",    "miner": "Acme Pool", "fee": 10})),
1919            ("2", serde_json::json!({"status": "pending", "miner": "acme solo", "fee": 20})),
1920            ("3", serde_json::json!({"status": "closed",  "miner": "Zenith",    "fee": 30})),
1921            ("4", serde_json::json!({"status": "open",    "fee": 40})),
1922            ("5", serde_json::json!({"status": "voided",  "miner": Value::Null, "fee": 50})),
1923        ];
1924        for (id, data) in rows {
1925            db.put("jobs", id, data, vec![], None, None).unwrap();
1926        }
1927        (dir, db)
1928    }
1929
1930    fn ids(rows: &[Value]) -> Vec<String> {
1931        let mut v: Vec<String> = rows.iter()
1932            .filter_map(|r| r["_id"].as_str().map(String::from))
1933            .collect();
1934        v.sort();
1935        v
1936    }
1937
1938    #[test]
1939    fn where_in_list() {
1940        let (_tmp, db) = setup();
1941        let (rows, _) = query(&db, "FROM blocks WHERE height IN (2, 4)").unwrap();
1942        assert_eq!(ids(&rows), vec!["2", "4"]);
1943    }
1944
1945    #[test]
1946    fn where_in_strings() {
1947        let (_tmp, db) = setup_text();
1948        let (rows, _) = query(&db, r#"FROM jobs WHERE status IN ("open", "closed")"#).unwrap();
1949        assert_eq!(ids(&rows), vec!["1", "3", "4"]);
1950    }
1951
1952    #[test]
1953    fn where_not_in() {
1954        let (_tmp, db) = setup();
1955        let (rows, _) = query(&db, "FROM blocks WHERE height NOT IN (1, 2, 3)").unwrap();
1956        assert_eq!(ids(&rows), vec!["4", "5"]);
1957    }
1958
1959    #[test]
1960    fn where_in_single_value_equals_eq() {
1961        let (_tmp, db) = setup();
1962        let (a, _) = query(&db, "FROM blocks WHERE height IN (3)").unwrap();
1963        let (b, _) = query(&db, "FROM blocks WHERE height = 3").unwrap();
1964        assert_eq!(ids(&a), ids(&b));
1965    }
1966
1967    #[test]
1968    fn where_between_is_inclusive() {
1969        let (_tmp, db) = setup();
1970        let (rows, _) = query(&db, "FROM blocks WHERE height BETWEEN 2 AND 4").unwrap();
1971        // SQL BETWEEN includes both bounds — 2 and 4 must be present.
1972        assert_eq!(ids(&rows), vec!["2", "3", "4"]);
1973    }
1974
1975    #[test]
1976    fn where_not_between() {
1977        let (_tmp, db) = setup();
1978        let (rows, _) = query(&db, "FROM blocks WHERE height NOT BETWEEN 2 AND 4").unwrap();
1979        assert_eq!(ids(&rows), vec!["1", "5"]);
1980    }
1981
1982    /// The AND inside BETWEEN belongs to BETWEEN, not to the conjunction
1983    /// parser. If parse_and grabbed it first, this query would fail to parse
1984    /// or silently lose the second bound.
1985    #[test]
1986    fn between_and_does_not_swallow_the_conjunction() {
1987        let (_tmp, db) = setup();
1988        let (rows, _) = query(
1989            &db, "FROM blocks WHERE height BETWEEN 2 AND 4 AND n_tx > 4").unwrap();
1990        // heights 2,3,4 then n_tx > 4 (n_tx = h*2) leaves 3 and 4.
1991        assert_eq!(ids(&rows), vec!["3", "4"]);
1992    }
1993
1994    #[test]
1995    fn where_like_prefix_suffix_and_infix() {
1996        let (_tmp, db) = setup_text();
1997        let (pre, _) = query(&db, r#"FROM jobs WHERE miner LIKE "Acme%""#).unwrap();
1998        assert_eq!(ids(&pre), vec!["1"]);
1999        let (suf, _) = query(&db, r#"FROM jobs WHERE miner LIKE "%Pool""#).unwrap();
2000        assert_eq!(ids(&suf), vec!["1"]);
2001        let (inf, _) = query(&db, r#"FROM jobs WHERE status LIKE "%pen%""#).unwrap();
2002        assert_eq!(ids(&inf), vec!["1", "2", "4"]);   // open, pending, open
2003    }
2004
2005    #[test]
2006    fn where_like_underscore_matches_exactly_one_char() {
2007        let (_tmp, db) = setup_text();
2008        let (rows, _) = query(&db, r#"FROM jobs WHERE status LIKE "open_""#).unwrap();
2009        assert!(rows.is_empty(), "`open_` must not match the 4-char value `open`");
2010        let (rows2, _) = query(&db, r#"FROM jobs WHERE status LIKE "ope_""#).unwrap();
2011        assert_eq!(ids(&rows2), vec!["1", "4"]);
2012    }
2013
2014    #[test]
2015    fn where_ilike_is_case_insensitive_and_like_is_not() {
2016        let (_tmp, db) = setup_text();
2017        let (ci, _) = query(&db, r#"FROM jobs WHERE miner ILIKE "acme%""#).unwrap();
2018        assert_eq!(ci.len(), 2, "ILIKE matches both `Acme Pool` and `acme solo`");
2019        let (cs, _) = query(&db, r#"FROM jobs WHERE miner LIKE "acme%""#).unwrap();
2020        assert_eq!(ids(&cs), vec!["2"], "LIKE stays case-sensitive");
2021    }
2022
2023    /// The backtracking path: multiple `%` with literals between them, where a
2024    /// greedy first match must be given back for the pattern to succeed.
2025    #[test]
2026    fn like_backtracks_across_multiple_wildcards() {
2027        assert!(like_match("abcabcabd", "%abc%abd", false));
2028        assert!(like_match("aaa", "%a", false));
2029        assert!(like_match("", "%", false));
2030        assert!(like_match("x", "%%%", false));
2031        assert!(!like_match("abc", "%abd", false));
2032        assert!(!like_match("ab", "ab_", false));
2033        assert!(like_match("héllo wörld", "h_llo w%d", false));
2034    }
2035
2036    // ── `~` / `!~` — the operator psql's catalogue filters need ─────────────
2037
2038    #[test]
2039    fn regex_anchors_behave_as_posix_says() {
2040        // THE case this exists for: psql's \dn sends `nspname !~ '^pg_'`.
2041        assert!(regex_match("pg_catalog", "^pg_", false));
2042        assert!(regex_match("pg_toast_1", "^pg_toast", false));
2043        assert!(!regex_match("public", "^pg_", false));
2044        // `^` only anchors at position 0 — a schema merely CONTAINING pg_ is
2045        // not a system schema, and treating it as one would hide a user's data.
2046        assert!(!regex_match("my_pg_stuff", "^pg_", false));
2047
2048        assert!(regex_match("report.sql", "sql$", false));
2049        assert!(!regex_match("sql_report", "sql$", false));
2050        // Anchored at both ends is an exact match.
2051        assert!(regex_match("public", "^public$", false));
2052        assert!(!regex_match("public2", "^public$", false));
2053        // Unanchored is a substring search.
2054        assert!(regex_match("xxpg_yy", "pg_", false));
2055        assert!(!regex_match("xxqg_yy", "pg_", false));
2056    }
2057
2058    #[test]
2059    fn regex_dot_matches_exactly_one_character() {
2060        assert!(regex_match("abc", "a.c", false));
2061        assert!(!regex_match("ac", "a.c", false), "`.` is one char, not zero");
2062        assert!(!regex_match("abbc", "a.c", false), "`.` is one char, not many");
2063        // Operates on chars, so a multi-byte value matches correctly.
2064        assert!(regex_match("héllo", "h.llo", false));
2065    }
2066
2067    #[test]
2068    fn regex_case_insensitivity_is_opt_in() {
2069        assert!(regex_match("PG_CATALOG", "^pg_", true));
2070        assert!(!regex_match("PG_CATALOG", "^pg_", false),
2071                "`~` is case SENSITIVE; only `~*` folds case");
2072    }
2073
2074    #[test]
2075    fn an_empty_regex_matches_anything() {
2076        // POSIX says so, and `$` alone is an empty anchored pattern.
2077        assert!(regex_match("anything", "", false));
2078        assert!(regex_match("", "", false));
2079        assert!(regex_match("x", "$", false));
2080    }
2081
2082    #[test]
2083    fn regex_groups_alternation_classes_and_quantifiers_match_as_ERE_says() {
2084        // THE case that forced the wider subset: `\d orders` sends
2085        // `relname ~ '^(orders)$'`, and `\d ord*` sends `^(ord.*)$`.
2086        assert!(regex_match("orders", "^(orders)$", false));
2087        assert!(!regex_match("orders2", "^(orders)$", false));
2088        assert!(regex_match("orders", "^(ord.*)$", false));
2089        assert!(regex_match("ord", "^(ord.*)$", false), "`.*` may match nothing");
2090        assert!(!regex_match("xord", "^(ord.*)$", false));
2091        // alternation, inside and outside a group
2092        assert!(regex_match("drivers", "^(orders|drivers)$", false));
2093        assert!(!regex_match("riders", "^(orders|drivers)$", false));
2094        assert!(regex_match("b", "a|b", false));
2095        // quantifiers are greedy and backtrack
2096        assert!(regex_match("aaab", "^a+b$", false));
2097        assert!(!regex_match("b", "^a+b$", false));
2098        assert!(regex_match("b", "^a*b$", false));
2099        assert!(regex_match("ab", "^a?b$", false));
2100        assert!(!regex_match("aab", "^a?b$", false));
2101        assert!(regex_match("aXb", "^a.+b$", false));
2102        // classes, ranges, negation, and a trailing literal `-`
2103        assert!(regex_match("pg_toast_9", "^pg_[a-z]+_[0-9]$", false));
2104        assert!(!regex_match("pg_toast_x", "^pg_[a-z]+_[0-9]$", false));
2105        assert!(regex_match("x", "^[^0-9]$", false));
2106        assert!(!regex_match("5", "^[^0-9]$", false));
2107        assert!(regex_match("a-b", "^a[-]b$", false));
2108        // an escape is the literal character, so `\.` is a dot and not "any"
2109        assert!(regex_match("a.b", "^a\\.b$", false));
2110        assert!(!regex_match("axb", "^a\\.b$", false));
2111        assert!(regex_match("(x)", "^\\(x\\)$", false));
2112        // `()*` must not loop forever: an empty repetition consumes nothing
2113        assert!(regex_match("q", "^()*q$", false));
2114        // operates on chars
2115        assert!(regex_match("héllo", "^h.l+o$", false));
2116    }
2117
2118    #[test]
2119    fn an_unsupported_regex_construct_is_REFUSED_BY_NAME_not_approximated() {
2120        // Matching `a{2,3}` approximately would silently include or exclude
2121        // rows, and a wrong catalogue listing looks exactly like a correct
2122        // one. So the parser refuses and names the construct.
2123        for (pat, needle) in [
2124            ("a{2}", "interval"),
2125            ("[[:alpha:]]", "POSIX character class"),
2126            ("(a)\\1", "back-reference"),
2127            ("\\d+", "shorthand class"),
2128            ("(ab", "unmatched '('"),
2129            ("ab)", "unmatched ')'"),
2130            ("[ab", "unmatched '['"),
2131            ("*a", "nothing to repeat"),
2132            ("[z-a]", "reversed"),
2133        ] {
2134            let why = regex_error(pat).unwrap_or_else(|| {
2135                panic!("{:?} must be refused, not matched approximately", pat)
2136            });
2137            assert!(why.contains(needle), "{:?}: {:?} should name {:?}", pat, why, needle);
2138            // And the matcher never answers for a pattern the parser refused.
2139            assert!(!regex_match("aa", pat, false));
2140        }
2141        for pat in ["^pg_", "sql$", "^public$", "a.c", "plain", "", "^(orders)$",
2142                    "a+b", "a*b", "a?b", "[ab]", "(a|b)", "a\\.b", "a[-]b"] {
2143            assert_eq!(regex_error(pat), None, "{:?} is in the subset", pat);
2144        }
2145    }
2146
2147    #[test]
2148    fn the_regex_operators_parse_in_all_four_spellings() {
2149        for (nql, negated, ci) in [
2150            (r#"FROM t WHERE nspname ~ "^pg_""#,   false, false),
2151            (r#"FROM t WHERE nspname ~* "^pg_""#,  false, true),
2152            (r#"FROM t WHERE nspname !~ "^pg_""#,  true,  false),
2153            (r#"FROM t WHERE nspname !~* "^pg_""#, true,  true),
2154        ] {
2155            let q = parse(nql).unwrap_or_else(|e| panic!("{}: {}", nql, e));
2156            match q.where_.expect("a predicate") {
2157                Pred::Regex { field, pattern, negated: n, ci: c } => {
2158                    assert_eq!(field, "nspname");
2159                    assert_eq!(pattern, "^pg_");
2160                    assert_eq!((n, c), (negated, ci), "{}", nql);
2161                }
2162                other => panic!("{} parsed as {:?}", nql, other),
2163            }
2164        }
2165    }
2166
2167    #[test]
2168    fn a_bad_regex_is_rejected_at_parse_time_with_the_offending_char() {
2169        let e = parse(r#"FROM t WHERE x ~ "a{2}""#).unwrap_err().to_string();
2170        assert!(e.contains("interval"), "the error must name the construct: {}", e);
2171        assert!(e.contains("refused"), "{}", e);
2172    }
2173
2174    #[test]
2175    fn a_regex_over_a_missing_field_is_false_in_both_polarities() {
2176        // SQL three-valued logic, matching LIKE and matching Postgres. psql's
2177        // catalogue filters depend on `!~` NOT resurrecting absent rows.
2178        let (_tmp, db) = setup_items();
2179        let (m, _) = query(&db, r#"FROM items WHERE nosuchfield ~ "x""#).unwrap();
2180        assert!(m.is_empty());
2181        let (n, _) = query(&db, r#"FROM items WHERE nosuchfield !~ "x""#).unwrap();
2182        assert!(n.is_empty(), "NOT over NULL must not match either");
2183    }
2184
2185    #[test]
2186    fn the_regex_operator_works_end_to_end_over_stored_documents() {
2187        let (_tmp, db) = setup_items();
2188        let (all, _) = query(&db, "FROM items").unwrap();
2189        let want: Vec<String> = all.iter()
2190            .filter_map(|r| r["_id"].as_str().map(str::to_string)).collect();
2191        // `_id` on every seeded item is non-empty, so an empty pattern matches
2192        // all of them — a control proving the operator reaches the executor.
2193        let (got, _) = query(&db, r#"FROM items WHERE _id ~ """#).unwrap();
2194        assert_eq!(got.len(), want.len());
2195        // And `!~` over the same pattern matches none.
2196        let (none, _) = query(&db, r#"FROM items WHERE _id !~ """#).unwrap();
2197        assert!(none.is_empty());
2198    }
2199
2200    #[test]
2201    fn where_not_like() {
2202        let (_tmp, db) = setup_text();
2203        let (rows, _) = query(&db, r#"FROM jobs WHERE status NOT LIKE "open""#).unwrap();
2204        assert_eq!(ids(&rows), vec!["2", "3", "5"]);
2205    }
2206
2207    /// NOT LIKE over a NULL/absent field stays false, as in SQL: a predicate
2208    /// over NULL is never true in either polarity. Rows 4 (absent) and 5
2209    /// (explicit null) must appear in NEITHER `LIKE` nor `NOT LIKE`.
2210    #[test]
2211    fn like_over_null_is_false_in_both_polarities() {
2212        let (_tmp, db) = setup_text();
2213        let (pos, _) = query(&db, r#"FROM jobs WHERE miner LIKE "%""#).unwrap();
2214        let (neg, _) = query(&db, r#"FROM jobs WHERE miner NOT LIKE "%""#).unwrap();
2215        assert!(!ids(&pos).contains(&"4".to_string()));
2216        assert!(!ids(&neg).contains(&"4".to_string()));
2217        assert!(!ids(&pos).contains(&"5".to_string()));
2218        assert!(!ids(&neg).contains(&"5".to_string()));
2219    }
2220
2221    /// Absent and explicitly-null are the same observable state in a
2222    /// schemaless store, so IS NULL must catch both.
2223    #[test]
2224    fn where_is_null_catches_absent_and_explicit_null() {
2225        let (_tmp, db) = setup_text();
2226        let (rows, _) = query(&db, "FROM jobs WHERE miner IS NULL").unwrap();
2227        assert_eq!(ids(&rows), vec!["4", "5"]);
2228    }
2229
2230    #[test]
2231    fn where_is_not_null() {
2232        let (_tmp, db) = setup_text();
2233        let (rows, _) = query(&db, "FROM jobs WHERE miner IS NOT NULL").unwrap();
2234        assert_eq!(ids(&rows), vec!["1", "2", "3"]);
2235    }
2236
2237    #[test]
2238    fn where_or() {
2239        let (_tmp, db) = setup();
2240        let (rows, _) = query(&db, "FROM blocks WHERE height = 1 OR height = 5").unwrap();
2241        assert_eq!(ids(&rows), vec!["1", "5"]);
2242    }
2243
2244    /// AND binds tighter than OR, so this is `a OR (b AND c)` and NOT
2245    /// `(a OR b) AND c`. With the wrong precedence the result would be [5].
2246    #[test]
2247    fn and_binds_tighter_than_or() {
2248        let (_tmp, db) = setup();
2249        let (rows, _) = query(
2250            &db, "FROM blocks WHERE height = 1 OR height = 5 AND n_tx = 10").unwrap();
2251        assert_eq!(ids(&rows), vec!["1", "5"]);
2252        let (rows2, _) = query(
2253            &db, "FROM blocks WHERE height = 1 OR height = 5 AND n_tx = 99").unwrap();
2254        assert_eq!(ids(&rows2), vec!["1"], "the AND arm must not match");
2255    }
2256
2257    /// Parentheses must be able to override that precedence.
2258    #[test]
2259    fn parens_override_precedence() {
2260        let (_tmp, db) = setup();
2261        let (rows, _) = query(
2262            &db, "FROM blocks WHERE (height = 1 OR height = 5) AND n_tx = 10").unwrap();
2263        assert_eq!(ids(&rows), vec!["5"]);
2264    }
2265
2266    #[test]
2267    fn nested_parens() {
2268        let (_tmp, db) = setup();
2269        let (rows, _) = query(
2270            &db,
2271            "FROM blocks WHERE ((height >= 2 AND height <= 4) OR height = 1) AND n_tx != 6",
2272        ).unwrap();
2273        assert_eq!(ids(&rows), vec!["1", "2", "4"]);
2274    }
2275
2276    #[test]
2277    fn not_negates_a_group() {
2278        let (_tmp, db) = setup();
2279        let (rows, _) = query(&db, "FROM blocks WHERE NOT (height > 2)").unwrap();
2280        assert_eq!(ids(&rows), vec!["1", "2"]);
2281    }
2282
2283    /// Prefix NOT before a bare comparison, as SQL allows. Distinct from the
2284    /// INFIX `field NOT <op>` form, which is a syntax error — only NOT IN /
2285    /// NOT BETWEEN / NOT LIKE exist in that position.
2286    #[test]
2287    fn prefix_not_before_a_comparison() {
2288        let (_tmp, db) = setup();
2289        let (rows, _) = query(&db, "FROM blocks WHERE NOT height = 1").unwrap();
2290        assert_eq!(ids(&rows), vec!["2", "3", "4", "5"]);
2291        let (double, _) = query(&db, "FROM blocks WHERE NOT NOT height = 1").unwrap();
2292        assert_eq!(ids(&double), vec!["1"]);
2293        let (mixed, _) = query(&db, "FROM blocks WHERE NOT height = 1 AND height < 4").unwrap();
2294        assert_eq!(ids(&mixed), vec!["2", "3"]);
2295    }
2296
2297    /// `_id = "x"` takes an O(1) index path. Under an OR it does not constrain
2298    /// the result set, so using it as a point lookup would drop every row the
2299    /// other arm matched. Guards the id_point_lookup AND-only descent.
2300    #[test]
2301    fn id_equality_under_or_does_not_become_a_point_lookup() {
2302        let (_tmp, db) = setup();
2303        let (rows, _) = query(&db, r#"FROM blocks WHERE _id = "1" OR height > 3"#).unwrap();
2304        assert_eq!(ids(&rows), vec!["1", "4", "5"],
2305                   "the OR arm must survive the id fast path");
2306    }
2307
2308    /// The fast path is still taken when the equality is a genuine conjunct.
2309    #[test]
2310    fn id_equality_under_and_still_point_looks_up() {
2311        let (_tmp, db) = setup();
2312        let (hit, _) = query(&db, r#"FROM blocks WHERE _id = "3" AND n_tx = 6"#).unwrap();
2313        assert_eq!(ids(&hit), vec!["3"]);
2314        let (miss, _) = query(&db, r#"FROM blocks WHERE _id = "3" AND n_tx = 999"#).unwrap();
2315        assert!(miss.is_empty(), "the second conjunct must still be applied");
2316    }
2317
2318    #[test]
2319    fn metadata_fields_are_filterable() {
2320        let (_tmp, db) = setup();
2321        // _seq is 0-indexed — the first put lands at seq 0, so `> 0` drops it.
2322        let (rows, _) = query(&db, "FROM blocks WHERE _seq >= 0 AND _coll = blocks").unwrap();
2323        assert_eq!(rows.len(), 5);
2324        let (tail, _) = query(&db, "FROM blocks WHERE _seq > 0").unwrap();
2325        assert_eq!(tail.len(), 4);
2326    }
2327
2328    #[test]
2329    fn combined_with_order_and_limit() {
2330        let (_tmp, db) = setup();
2331        let (rows, _) = query(
2332            &db,
2333            "FROM blocks WHERE height IN (1, 3, 5) ORDER BY height DESC LIMIT 2",
2334        ).unwrap();
2335        let heights: Vec<u64> = rows.iter().filter_map(|r| r["height"].as_u64()).collect();
2336        assert_eq!(heights, vec![5, 3]);
2337    }
2338
2339    // ── Strictness: a query the engine cannot honour must FAIL, not lie ──────
2340
2341    /// The headline regression. `_ => { self.advance(); }` meant an
2342    /// unimplemented or misspelled clause was dropped and a DIFFERENT query
2343    /// was answered. Each of these previously returned rows.
2344    #[test]
2345    fn unknown_clauses_are_errors_not_silent_skips() {
2346        let (_tmp, db) = setup();
2347        for bad in [
2348            "FROM blocks ORDRE BY height",       // typo
2349            "FROM blocks WHERE height > 3 JUNK", // trailing garbage
2350            "FROM blocks SELECT height",         // wrong dialect
2351            "FROM blocks LIMIT",                 // missing count
2352            "FROM blocks OFFSET",                // missing count
2353            "FROM blocks ORDER BY",              // missing key
2354            "FROM blocks ORDER BY height,",      // trailing comma
2355        ] {
2356            assert!(query(&db, bad).is_err(), "`{}` must be rejected, not silently reinterpreted", bad);
2357        }
2358    }
2359
2360    #[test]
2361    fn malformed_predicates_are_errors() {
2362        let (_tmp, db) = setup();
2363        for bad in [
2364            "FROM blocks WHERE height >",            // missing value
2365            "FROM blocks WHERE height IN (",         // unterminated list
2366            "FROM blocks WHERE height IN ()",        // empty list
2367            "FROM blocks WHERE height BETWEEN 1",    // missing AND high
2368            "FROM blocks WHERE height BETWEEN 1 3",  // missing AND
2369            "FROM blocks WHERE (height = 1",         // unbalanced paren
2370            "FROM blocks WHERE height IS 3",         // IS without NULL
2371            "FROM blocks WHERE height NOT = 1",      // infix NOT before a comparison op
2372            "FROM blocks WHERE height LIKE",         // missing pattern
2373        ] {
2374            assert!(query(&db, bad).is_err(), "`{}` must be a parse error", bad);
2375        }
2376    }
2377
2378    /// ASC used to survive only because unknown tokens were skipped. Now that
2379    /// skipping is gone it has to be a real keyword, and the pre-existing
2380    /// `order_by_limit` test above depends on it.
2381    #[test]
2382    fn asc_is_accepted_explicitly() {
2383        let (_tmp, db) = setup();
2384        let (asc, _) = query(&db, "FROM blocks ORDER BY height ASC").unwrap();
2385        let (plain, _) = query(&db, "FROM blocks ORDER BY height").unwrap();
2386        assert_eq!(asc[0]["height"], 1);
2387        assert_eq!(plain[0]["height"], 1);
2388    }
2389
2390    /// Lowercase and mixed-case keywords must keep working — the lexer
2391    /// uppercases before matching, and the new keywords must be no different.
2392    #[test]
2393    fn new_keywords_are_case_insensitive() {
2394        let (_tmp, db) = setup();
2395        let (rows, _) = query(&db, "from blocks where height between 2 and 3").unwrap();
2396        assert_eq!(ids(&rows), vec!["2", "3"]);
2397        let (rows2, _) = query(&db, "FROM blocks Where height In (1) Or height In (2)").unwrap();
2398        assert_eq!(ids(&rows2), vec!["1", "2"]);
2399    }
2400
2401    #[test]
2402    fn group_by_count() {
2403        let (_tmp, db) = setup();
2404        let (rows, _) = query(&db, "FROM blocks GROUP BY n_tx COUNT").unwrap();
2405        assert_eq!(rows.len(), 5); // all unique n_tx values
2406    }
2407
2408    // ── Indexed range / point scans (3.3.0) ─────────────────────────────────
2409    //
2410    // The load-bearing property is EQUIVALENCE: an indexed query and the same
2411    // query without an index must return the same rows. The planner is allowed
2412    // to be imprecise (it only has to produce a superset — the full predicate
2413    // re-runs on the candidates) but it is never allowed to be wrong.
2414    //
2415    // Every test below therefore runs the same query against two databases
2416    // holding identical data, one indexed and one not, and compares.
2417
2418    /// Build two identical databases, one with sorted indexes on `fields`.
2419    fn twin(fields: &[&str]) -> (tempfile::TempDir, tempfile::TempDir, Db, Db) {
2420        let d1 = tempdir().unwrap();
2421        let d2 = tempdir().unwrap();
2422        let indexed = Db::open(d1.path(), None).unwrap();
2423        let plain = Db::open(d2.path(), None).unwrap();
2424        for f in fields {
2425            indexed.create_sorted_index("t", f);
2426        }
2427        // Deliberately messy: duplicate fees, a missing field, a null, a
2428        // string column, and an out-of-order insert sequence.
2429        let rows: Vec<(String, Value)> = (0..40u64).map(|i| {
2430            let mut o = serde_json::Map::new();
2431            if i % 7 != 0 {
2432                o.insert("fee".into(), json!(i % 13));
2433            }
2434            if i % 11 == 0 {
2435                o.insert("note".into(), Value::Null);
2436            } else {
2437                o.insert("note".into(), json!(format!("n{}", i % 5)));
2438            }
2439            o.insert("rank".into(), json!(40 - i));
2440            (i.to_string(), Value::Object(o))
2441        }).collect();
2442        for (id, doc) in &rows {
2443            indexed.put("t", id, doc.clone(), vec![], None, None).unwrap();
2444            plain.put("t", id, doc.clone(), vec![], None, None).unwrap();
2445        }
2446        (d1, d2, indexed, plain)
2447    }
2448
2449    fn same(a: &Db, b: &Db, nql: &str) -> (Vec<String>, Vec<String>) {
2450        let ga = {
2451            let (rows, _) = query(a, nql).unwrap();
2452            let mut v: Vec<String> = rows.iter()
2453                .filter_map(|r| r["_id"].as_str().map(String::from)).collect();
2454            v.sort(); v
2455        };
2456        let gb = {
2457            let (rows, _) = query(b, nql).unwrap();
2458            let mut v: Vec<String> = rows.iter()
2459                .filter_map(|r| r["_id"].as_str().map(String::from)).collect();
2460            v.sort(); v
2461        };
2462        (ga, gb)
2463    }
2464
2465    #[test]
2466    fn indexed_and_unindexed_agree_on_every_predicate_shape() {
2467        let (_t1, _t2, idx, plain) = twin(&["fee", "note", "rank"]);
2468        for nql in [
2469            // ranges — the shapes the index now serves
2470            "FROM t WHERE fee > 5",
2471            "FROM t WHERE fee >= 5",
2472            "FROM t WHERE fee < 5",
2473            "FROM t WHERE fee <= 5",
2474            "FROM t WHERE fee = 5",
2475            "FROM t WHERE fee BETWEEN 3 AND 8",
2476            "FROM t WHERE fee NOT BETWEEN 3 AND 8",
2477            "FROM t WHERE fee IN (1, 5, 9)",
2478            "FROM t WHERE fee NOT IN (1, 5, 9)",
2479            "FROM t WHERE fee != 5",
2480            // merged bounds on one field
2481            "FROM t WHERE fee > 3 AND fee < 9",
2482            "FROM t WHERE fee >= 3 AND fee <= 9",
2483            "FROM t WHERE fee > 3 AND fee < 9 AND fee != 5",
2484            "FROM t WHERE fee BETWEEN 2 AND 10 AND fee > 6",
2485            // two indexed fields — the planner must pick one and stay correct
2486            "FROM t WHERE fee > 5 AND rank < 20",
2487            "FROM t WHERE fee IN (2, 3) AND rank > 10",
2488            "FROM t WHERE fee = 4 AND rank = 8",
2489            // the absent-field cases, where a naive index scan inverts the answer
2490            "FROM t WHERE fee IS NULL",
2491            "FROM t WHERE fee IS NOT NULL",
2492            "FROM t WHERE note IS NULL",
2493            "FROM t WHERE note IS NOT NULL",
2494            "FROM t WHERE fee IS NULL AND rank > 20",
2495            // predicates the index cannot serve, mixed with ones it can
2496            r#"FROM t WHERE note LIKE "n_""#,
2497            r#"FROM t WHERE fee > 5 AND note LIKE "n1""#,
2498            r#"FROM t WHERE note NOT LIKE "n1" AND fee < 4"#,
2499            // disjunction — must NOT be narrowed on one arm
2500            "FROM t WHERE fee > 11 OR rank > 38",
2501            "FROM t WHERE fee = 1 OR note IS NULL",
2502            "FROM t WHERE (fee > 11 OR rank > 38) AND rank < 39",
2503            "FROM t WHERE fee IN (1) OR fee IN (2)",
2504            // negation
2505            "FROM t WHERE NOT (fee > 5)",
2506            "FROM t WHERE NOT (fee IN (1, 2))",
2507            "FROM t WHERE NOT (fee > 5) AND rank < 30",
2508            // with shaping on top
2509            "FROM t WHERE fee > 5 ORDER BY rank DESC LIMIT 5",
2510            "FROM t WHERE fee BETWEEN 2 AND 8 ORDER BY fee, rank DESC",
2511            "FROM t WHERE fee > 5 GROUP BY note COUNT",
2512            "FROM t WHERE fee > 5 COUNT",
2513            "FROM t WHERE fee > 5 ORDER BY rank LIMIT 3 OFFSET 2",
2514            // empty results
2515            "FROM t WHERE fee > 9999",
2516            "FROM t WHERE fee IN (9999)",
2517            "FROM t WHERE fee BETWEEN 100 AND 200",
2518        ] {
2519            let (a, b) = same(&idx, &plain, nql);
2520            assert_eq!(a, b, "indexed and unindexed disagree on `{}`", nql);
2521        }
2522    }
2523
2524    /// Ordering, not just membership, must survive the index path — the
2525    /// candidates arrive in index order of the PREDICATE field, which is not
2526    /// the requested sort order, so the post-filter sort has to still run.
2527    #[test]
2528    fn index_path_still_honours_order_by() {
2529        let (_t1, _t2, idx, plain) = twin(&["fee", "rank"]);
2530        for nql in [
2531            "FROM t WHERE fee > 4 ORDER BY rank",
2532            "FROM t WHERE fee > 4 ORDER BY rank DESC",
2533            "FROM t WHERE fee > 4 ORDER BY note, rank DESC",
2534            "FROM t WHERE fee BETWEEN 2 AND 9 ORDER BY rank LIMIT 4",
2535            "FROM t WHERE fee IN (3, 6) ORDER BY rank DESC LIMIT 2",
2536        ] {
2537            let ra = query(&idx, nql).unwrap().0;
2538            let rb = query(&plain, nql).unwrap().0;
2539            let ia: Vec<&str> = ra.iter().filter_map(|r| r["_id"].as_str()).collect();
2540            let ib: Vec<&str> = rb.iter().filter_map(|r| r["_id"].as_str()).collect();
2541            assert_eq!(ia, ib, "row ORDER differs on `{}`", nql);
2542        }
2543    }
2544
2545    /// An ordering comparison against a missing field is never true.
2546    ///
2547    /// OrderedValue sorts Null below every number, so `<` and `<=` reported
2548    /// that a document with NO `fee` field satisfied `WHERE fee < 5` — while
2549    /// `>` and `>=` excluded it. That asymmetry was the tell. The Python
2550    /// reference has always excluded it, so this was a cross-engine
2551    /// divergence as well as a wrong answer, and it meant the scan path and
2552    /// the index path disagreed depending on whether an index existed.
2553    #[test]
2554    fn an_ordering_comparison_against_a_missing_field_is_false() {
2555        let dir = tempdir().unwrap();
2556        let db = Db::open(dir.path(), None).unwrap();
2557        db.put("t", "has", json!({"fee": 1}), vec![], None, None).unwrap();
2558        db.put("t", "none", json!({"other": 1}), vec![], None, None).unwrap();
2559        db.put("t", "null", json!({"fee": Value::Null}), vec![], None, None).unwrap();
2560
2561        for nql in ["FROM t WHERE fee < 5", "FROM t WHERE fee <= 5"] {
2562            let (r, _) = query(&db, nql).unwrap();
2563            let ids: Vec<&str> = r.iter().filter_map(|x| x["_id"].as_str()).collect();
2564            assert_eq!(ids, vec!["has"],
2565                       "`{}` must not match a row whose fee is absent or null", nql);
2566        }
2567        for nql in ["FROM t WHERE fee > 0", "FROM t WHERE fee >= 0"] {
2568            let (r, _) = query(&db, nql).unwrap();
2569            let ids: Vec<&str> = r.iter().filter_map(|x| x["_id"].as_str()).collect();
2570            assert_eq!(ids, vec!["has"], "`{}`", nql);
2571        }
2572        // BETWEEN is built from >= and <=, so it inherits the rule.
2573        let (b, _) = query(&db, "FROM t WHERE fee BETWEEN 0 AND 9").unwrap();
2574        assert_eq!(b.len(), 1);
2575
2576        // = and != keep operating on null, exactly as the Python reference
2577        // does — its None guard sits deliberately AFTER those two arms.
2578        let (ne, _) = query(&db, "FROM t WHERE fee != 5").unwrap();
2579        assert_eq!(ne.len(), 3, "!= still matches absent and null fields");
2580        let (isnull, _) = query(&db, "FROM t WHERE fee = NULL").unwrap();
2581        assert_eq!(isnull.len(), 2, "absent and explicit-null both equal NULL");
2582
2583        // And the same answers with an index present — the two paths agreeing
2584        // is the reason this fix was required, not merely desirable.
2585        let d2 = tempdir().unwrap();
2586        let idx = Db::open(d2.path(), None).unwrap();
2587        idx.create_sorted_index("t", "fee");
2588        idx.put("t", "has", json!({"fee": 1}), vec![], None, None).unwrap();
2589        idx.put("t", "none", json!({"other": 1}), vec![], None, None).unwrap();
2590        idx.put("t", "null", json!({"fee": Value::Null}), vec![], None, None).unwrap();
2591        for nql in ["FROM t WHERE fee < 5", "FROM t WHERE fee <= 5",
2592                    "FROM t WHERE fee > 0", "FROM t WHERE fee BETWEEN 0 AND 9"] {
2593            let (a, _) = query(&db, nql).unwrap();
2594            let (b, _) = query(&idx, nql).unwrap();
2595            let ia: Vec<&str> = a.iter().filter_map(|x| x["_id"].as_str()).collect();
2596            let ib: Vec<&str> = b.iter().filter_map(|x| x["_id"].as_str()).collect();
2597            assert_eq!(ia, ib, "indexed and unindexed disagree on `{}`", nql);
2598        }
2599    }
2600
2601    /// `IS NULL` must never touch this index. A document whose field is absent
2602    /// is not in the index for that field, so an index scan would return
2603    /// exactly the complement of the right answer — the worst possible failure
2604    /// for a filter, since it looks like a plausible result set.
2605    #[test]
2606    fn is_null_never_uses_the_index() {
2607        let (_t1, _t2, idx, plain) = twin(&["fee"]);
2608        let (a, b) = same(&idx, &plain, "FROM t WHERE fee IS NULL");
2609        assert_eq!(a, b);
2610        // 40 docs, every 7th missing `fee`: ids 0,7,14,21,28,35.
2611        assert_eq!(a, vec!["0", "14", "21", "28", "35", "7"]);
2612        assert!(!a.is_empty(), "the fixture must actually contain absent fields");
2613    }
2614
2615    /// A constraint under an OR does not restrict the result set, so the
2616    /// planner must not narrow on it. Both arms have to survive.
2617    #[test]
2618    fn a_disjunct_is_never_used_to_narrow() {
2619        let (_t1, _t2, idx, plain) = twin(&["fee", "rank"]);
2620        let nql = "FROM t WHERE fee = 1 OR rank = 40";
2621        let (a, b) = same(&idx, &plain, nql);
2622        assert_eq!(a, b);
2623        // rank = 40 is doc 0, which has NO `fee` field at all — so if the
2624        // planner had narrowed on the `fee` arm it would have been dropped.
2625        assert!(a.contains(&"0".to_string()),
2626                "the OR arm matching a doc with no indexed field must survive: {:?}", a);
2627        assert!(a.len() > 1, "both arms must contribute: {:?}", a);
2628    }
2629
2630    /// AS OF must not use the index: it holds CURRENT versions only, because a
2631    /// superseded hash is removed on overwrite. An index scan would answer a
2632    /// historical query with present-day rows.
2633    #[test]
2634    fn as_of_does_not_use_the_current_version_index() {
2635        let dir = tempdir().unwrap();
2636        let db = Db::open(dir.path(), None).unwrap();
2637        db.create_sorted_index("t", "fee");
2638        db.put("t", "a", json!({"fee": 5}), vec![], None, None).unwrap();
2639        let snap = db.put("t", "b", json!({"fee": 5}), vec![], None, None).unwrap().seq;
2640        // Move both out of the range the query asks for.
2641        db.put("t", "a", json!({"fee": 999}), vec![], None, None).unwrap();
2642        db.put("t", "b", json!({"fee": 999}), vec![], None, None).unwrap();
2643
2644        // At HEAD nothing matches fee = 5 any more.
2645        let (now, _) = query(&db, "FROM t WHERE fee = 5").unwrap();
2646        assert!(now.is_empty(), "current versions have fee 999: {:?}", now);
2647
2648        // AS OF the snapshot, both still had fee = 5. If the index served
2649        // this, it would return nothing.
2650        let (then, _) = query(&db, &format!("FROM t AS OF {} WHERE fee = 5", snap)).unwrap();
2651        let mut ids: Vec<&str> = then.iter().filter_map(|r| r["_id"].as_str()).collect();
2652        ids.sort();
2653        assert_eq!(ids, vec!["a", "b"], "AS OF must see the historical values");
2654
2655        // Same for a range and an IN.
2656        let (r, _) = query(&db, &format!("FROM t AS OF {} WHERE fee BETWEEN 1 AND 9", snap)).unwrap();
2657        assert_eq!(r.len(), 2);
2658        let (i, _) = query(&db, &format!("FROM t AS OF {} WHERE fee IN (5)", snap)).unwrap();
2659        assert_eq!(i.len(), 2);
2660    }
2661
2662    /// An overwritten row must not come back from the index.
2663    #[test]
2664    fn the_index_path_returns_current_versions_only() {
2665        let dir = tempdir().unwrap();
2666        let db = Db::open(dir.path(), None).unwrap();
2667        db.create_sorted_index("t", "fee");
2668        for i in 0..5u64 {
2669            db.put("t", &i.to_string(), json!({"fee": i}), vec![], None, None).unwrap();
2670        }
2671        db.put("t", "0", json!({"fee": 100}), vec![], None, None).unwrap();
2672
2673        let (low, _) = query(&db, "FROM t WHERE fee BETWEEN 0 AND 4").unwrap();
2674        let mut ids: Vec<&str> = low.iter().filter_map(|r| r["_id"].as_str()).collect();
2675        ids.sort();
2676        assert_eq!(ids, vec!["1", "2", "3", "4"],
2677                   "doc 0 moved to fee 100 and must not appear in 0..4");
2678
2679        let (high, _) = query(&db, "FROM t WHERE fee = 100").unwrap();
2680        assert_eq!(high.len(), 1);
2681        assert_eq!(high[0]["_id"], "0");
2682        assert_eq!(high[0]["fee"], json!(100), "the CURRENT value, not the old one");
2683    }
2684
2685    /// Duplicate values must not produce duplicate rows, and a value repeated
2686    /// across IN arms must be returned once.
2687    #[test]
2688    fn index_scans_do_not_duplicate_rows() {
2689        let dir = tempdir().unwrap();
2690        let db = Db::open(dir.path(), None).unwrap();
2691        db.create_sorted_index("t", "fee");
2692        for i in 0..6u64 {
2693            db.put("t", &i.to_string(), json!({"fee": i % 2}), vec![], None, None).unwrap();
2694        }
2695        let (dup, _) = query(&db, "FROM t WHERE fee IN (0, 0, 1, 1)").unwrap();
2696        assert_eq!(dup.len(), 6, "each row once despite repeated IN arms");
2697        let (r, _) = query(&db, "FROM t WHERE fee BETWEEN 0 AND 1").unwrap();
2698        assert_eq!(r.len(), 6);
2699        let mut ids: Vec<&str> = dup.iter().filter_map(|r| r["_id"].as_str()).collect();
2700        ids.sort();
2701        ids.dedup();
2702        assert_eq!(ids.len(), 6, "no duplicate _ids");
2703    }
2704
2705    /// A range over a string column, to prove the index is not numeric-only.
2706    #[test]
2707    fn index_ranges_work_on_strings() {
2708        let dir = tempdir().unwrap();
2709        let db = Db::open(dir.path(), None).unwrap();
2710        db.create_sorted_index("t", "name");
2711        for (i, n) in ["alpha", "bravo", "charlie", "delta", "echo"].iter().enumerate() {
2712            db.put("t", &i.to_string(), json!({"name": n}), vec![], None, None).unwrap();
2713        }
2714        let (r, _) = query(&db, r#"FROM t WHERE name BETWEEN "bravo" AND "delta""#).unwrap();
2715        let mut got: Vec<&str> = r.iter().filter_map(|x| x["name"].as_str()).collect();
2716        got.sort();
2717        assert_eq!(got, vec!["bravo", "charlie", "delta"]);
2718        let (gt, _) = query(&db, r#"FROM t WHERE name > "charlie""#).unwrap();
2719        assert_eq!(gt.len(), 2);
2720    }
2721
2722    /// Bounds must be merged into one walk, and the tighter bound must win
2723    /// regardless of the order the conjuncts appear in.
2724    #[test]
2725    fn same_field_bounds_are_merged_tightest_wins() {
2726        let (_t1, _t2, idx, plain) = twin(&["fee"]);
2727        for (a_nql, b_nql) in [
2728            ("FROM t WHERE fee > 2 AND fee > 6", "FROM t WHERE fee > 6"),
2729            ("FROM t WHERE fee > 6 AND fee > 2", "FROM t WHERE fee > 6"),
2730            ("FROM t WHERE fee < 9 AND fee < 4", "FROM t WHERE fee < 4"),
2731            ("FROM t WHERE fee BETWEEN 0 AND 12 AND fee >= 5 AND fee <= 7",
2732             "FROM t WHERE fee >= 5 AND fee <= 7"),
2733        ] {
2734            let (ia, _) = same(&idx, &plain, a_nql);
2735            let (ib, _) = same(&idx, &plain, b_nql);
2736            assert_eq!(ia, ib, "`{}` should equal `{}`", a_nql, b_nql);
2737        }
2738    }
2739
2740    /// The index only helps where it exists; an unindexed field must still
2741    /// answer correctly through the scan path.
2742    #[test]
2743    fn a_predicate_on_an_unindexed_field_still_answers() {
2744        let (_t1, _t2, idx, plain) = twin(&["fee"]);   // `rank` is NOT indexed
2745        for nql in [
2746            "FROM t WHERE rank > 30",
2747            "FROM t WHERE rank BETWEEN 10 AND 20",
2748            "FROM t WHERE rank IN (40, 39)",
2749            "FROM t WHERE rank > 30 AND fee > 2",
2750        ] {
2751            let (a, b) = same(&idx, &plain, nql);
2752            assert_eq!(a, b, "`{}`", nql);
2753        }
2754    }
2755
2756    /// Cardinality is reported off the index without reading any rows, which
2757    /// is what lets the planner compare two candidate indexes.
2758    #[test]
2759    fn range_cardinality_counts_without_reading() {
2760        let dir = tempdir().unwrap();
2761        let db = Db::open(dir.path(), None).unwrap();
2762        db.create_sorted_index("t", "fee");
2763        for i in 0..20u64 {
2764            db.put("t", &i.to_string(), json!({"fee": i}), vec![], None, None).unwrap();
2765        }
2766        assert_eq!(db.range_cardinality("t", "fee", None, None, true, true), Some(20));
2767        assert_eq!(
2768            db.range_cardinality("t", "fee", Some(&json!(5)), Some(&json!(9)), true, true),
2769            Some(5), "5..=9 inclusive is five values");
2770        assert_eq!(
2771            db.range_cardinality("t", "fee", Some(&json!(5)), Some(&json!(9)), false, false),
2772            Some(3), "exclusive bounds drop both ends");
2773        assert_eq!(
2774            db.range_cardinality("t", "fee", Some(&json!(18)), None, true, true),
2775            Some(2));
2776        assert_eq!(
2777            db.range_cardinality("t", "fee", Some(&json!(999)), None, true, true),
2778            Some(0), "an empty range is 0, not an error");
2779        // No index on this field at all.
2780        assert_eq!(db.range_cardinality("t", "nope", None, None, true, true), None);
2781    }
2782
2783    /// With two usable indexes the planner should choose the narrower range.
2784    /// Asserted through cardinality rather than by inspecting the plan, so the
2785    /// test pins the observable behaviour and not the implementation.
2786    #[test]
2787    fn the_narrower_index_is_preferred() {
2788        let dir = tempdir().unwrap();
2789        let db = Db::open(dir.path(), None).unwrap();
2790        db.create_sorted_index("t", "wide");
2791        db.create_sorted_index("t", "narrow");
2792        for i in 0..100u64 {
2793            db.put("t", &i.to_string(),
2794                   json!({"wide": i % 2, "narrow": i}), vec![], None, None).unwrap();
2795        }
2796        // `wide = 0` covers 50 rows; `narrow = 7` covers 1.
2797        let wide = db.range_cardinality("t", "wide", Some(&json!(0)), Some(&json!(0)), true, true);
2798        let narrow = db.range_cardinality("t", "narrow", Some(&json!(7)), Some(&json!(7)), true, true);
2799        assert_eq!(wide, Some(50));
2800        assert_eq!(narrow, Some(1));
2801        // The answer must be right whichever index is chosen.
2802        let (r, _) = query(&db, "FROM t WHERE wide = 0 AND narrow = 7").unwrap();
2803        assert!(r.is_empty(), "narrow 7 has wide 1, so nothing matches");
2804        let (r2, _) = query(&db, "FROM t WHERE wide = 0 AND narrow = 8").unwrap();
2805        assert_eq!(r2.len(), 1);
2806        assert_eq!(r2[0]["_id"], "8");
2807    }
2808
2809    // ── Result shaping (3.3.0): OFFSET, multi-key ORDER BY, HAVING, ─────────
2810    // ── bare aggregates, and the SQL pipeline order ─────────────────────────
2811
2812    fn heights(rows: &[Value]) -> Vec<u64> {
2813        rows.iter().filter_map(|r| r["height"].as_u64()).collect()
2814    }
2815
2816    #[test]
2817    fn offset_skips_result_rows() {
2818        let (_tmp, db) = setup();
2819        let (rows, _) = query(&db, "FROM blocks ORDER BY height OFFSET 2").unwrap();
2820        assert_eq!(heights(&rows), vec![3, 4, 5]);
2821    }
2822
2823    #[test]
2824    fn offset_with_limit_pages() {
2825        let (_tmp, db) = setup();
2826        // Page through 5 rows two at a time. Each page must be disjoint and
2827        // in order — the bug to catch is a pushdown that fetches only `limit`
2828        // rows and therefore returns page 1 for every page.
2829        let mut seen = vec![];
2830        for page in 0..3 {
2831            let (rows, _) = query(
2832                &db,
2833                &format!("FROM blocks ORDER BY height LIMIT 2 OFFSET {}", page * 2),
2834            ).unwrap();
2835            seen.extend(heights(&rows));
2836        }
2837        assert_eq!(seen, vec![1, 2, 3, 4, 5]);
2838    }
2839
2840    #[test]
2841    fn offset_past_the_end_is_an_empty_page() {
2842        let (_tmp, db) = setup();
2843        let (rows, count) = query(&db, "FROM blocks OFFSET 99").unwrap();
2844        assert!(rows.is_empty());
2845        assert_eq!(count, 0);
2846        let (zero, _) = query(&db, "FROM blocks OFFSET 0").unwrap();
2847        assert_eq!(zero.len(), 5, "OFFSET 0 skips nothing");
2848    }
2849
2850    #[test]
2851    fn offset_applies_after_the_filter() {
2852        let (_tmp, db) = setup();
2853        // n_tx = h*2, so `>= 6` matches heights 3,4,5. Offsetting by one must
2854        // skip the first MATCH, not the first row of the collection.
2855        let (rows, _) = query(
2856            &db, "FROM blocks WHERE n_tx >= 6 ORDER BY height OFFSET 1").unwrap();
2857        assert_eq!(heights(&rows), vec![4, 5]);
2858    }
2859
2860    #[test]
2861    fn order_by_multiple_keys() {
2862        let dir = tempdir().unwrap();
2863        let db = Db::open(dir.path(), None).unwrap();
2864        // Two statuses, each with several fees, so the second key has to do
2865        // real work to break the first key's ties.
2866        for (i, (s, f)) in [("open", 30), ("open", 10), ("closed", 20),
2867                            ("open", 20), ("closed", 5)].iter().enumerate() {
2868            db.put("t", &i.to_string(),
2869                serde_json::json!({"status": s, "fee": f}), vec![], None, None).unwrap();
2870        }
2871        let (rows, _) = query(&db, "FROM t ORDER BY status, fee DESC").unwrap();
2872        let got: Vec<(String, u64)> = rows.iter()
2873            .map(|r| (r["status"].as_str().unwrap().to_string(), r["fee"].as_u64().unwrap()))
2874            .collect();
2875        assert_eq!(got, vec![
2876            ("closed".into(), 20), ("closed".into(), 5),
2877            ("open".into(), 30), ("open".into(), 20), ("open".into(), 10),
2878        ]);
2879    }
2880
2881    #[test]
2882    fn order_by_mixed_directions() {
2883        let dir = tempdir().unwrap();
2884        let db = Db::open(dir.path(), None).unwrap();
2885        for (i, (a, b)) in [(1, 1), (1, 2), (2, 1), (2, 2)].iter().enumerate() {
2886            db.put("t", &i.to_string(),
2887                serde_json::json!({"a": a, "b": b}), vec![], None, None).unwrap();
2888        }
2889        let (rows, _) = query(&db, "FROM t ORDER BY a DESC, b ASC").unwrap();
2890        let got: Vec<(u64, u64)> = rows.iter()
2891            .map(|r| (r["a"].as_u64().unwrap(), r["b"].as_u64().unwrap()))
2892            .collect();
2893        assert_eq!(got, vec![(2, 1), (2, 2), (1, 1), (1, 2)]);
2894    }
2895
2896    /// The headline pipeline-order bug. In SQL, LIMIT applies to the RESULT.
2897    /// The old order was ORDER BY -> LIMIT -> GROUP BY, so LIMIT truncated the
2898    /// INPUT and the aggregate was computed over a fraction of the rows —
2899    /// reporting counts that summed to the limit instead of the true total.
2900    #[test]
2901    fn limit_applies_to_grouped_rows_not_to_the_input() {
2902        let dir = tempdir().unwrap();
2903        let db = Db::open(dir.path(), None).unwrap();
2904        for i in 0..12 {
2905            // Hoisted: json! cannot parse an indexing expression inline.
2906            let status = ["open", "closed", "void"][i % 3];
2907            db.put("t", &i.to_string(),
2908                serde_json::json!({"status": status, "fee": i}),
2909                vec![], None, None).unwrap();
2910        }
2911        let (all, _) = query(&db, "FROM t GROUP BY status COUNT").unwrap();
2912        assert_eq!(all.len(), 3);
2913        let total: u64 = all.iter().filter_map(|r| r["count"].as_u64()).sum();
2914        assert_eq!(total, 12, "every input row must be counted");
2915
2916        // LIMIT 2 must return 2 GROUPS, each with its full count — not two
2917        // input rows regrouped.
2918        let (limited, _) = query(&db, "FROM t GROUP BY status COUNT LIMIT 2").unwrap();
2919        assert_eq!(limited.len(), 2, "LIMIT caps the number of groups");
2920        for r in &limited {
2921            assert_eq!(r["count"], json!(4),
2922                       "each group keeps its true count, got {:?}", r);
2923        }
2924    }
2925
2926    /// The second pipeline-order bug: ORDER BY ran before grouping, so it
2927    /// sorted the raw documents on a field that only exists AFTER grouping
2928    /// (`count`, `sum_fee`) and the grouped output came back unordered. The
2929    /// clause was silently inert.
2930    #[test]
2931    fn order_by_sorts_the_grouped_rows() {
2932        let dir = tempdir().unwrap();
2933        let db = Db::open(dir.path(), None).unwrap();
2934        // Deliberately uneven: 1 x "a", 3 x "b", 2 x "c".
2935        for (i, s) in ["a", "b", "b", "b", "c", "c"].iter().enumerate() {
2936            db.put("t", &i.to_string(),
2937                serde_json::json!({"g": s, "n": i}), vec![], None, None).unwrap();
2938        }
2939        let (rows, _) = query(&db, "FROM t GROUP BY g COUNT ORDER BY count DESC").unwrap();
2940        let got: Vec<(String, u64)> = rows.iter()
2941            .map(|r| (r["g"].as_str().unwrap().to_string(), r["count"].as_u64().unwrap()))
2942            .collect();
2943        assert_eq!(got, vec![("b".into(), 3), ("c".into(), 2), ("a".into(), 1)]);
2944
2945        // And the group key itself is sortable.
2946        let (by_key, _) = query(&db, "FROM t GROUP BY g COUNT ORDER BY g DESC").unwrap();
2947        let keys: Vec<&str> = by_key.iter().map(|r| r["g"].as_str().unwrap()).collect();
2948        assert_eq!(keys, vec!["c", "b", "a"]);
2949    }
2950
2951    #[test]
2952    fn order_by_an_aggregate_key() {
2953        let (_tmp, db) = setup_items();
2954        let (rows, _) = query(
2955            &db, "FROM items GROUP BY cat SUM price ORDER BY sum_price DESC").unwrap();
2956        let cats: Vec<&str> = rows.iter().map(|r| r["cat"].as_str().unwrap()).collect();
2957        assert_eq!(cats, vec!["y", "x"], "y sums to 60, x to 15");
2958    }
2959
2960    #[test]
2961    fn offset_and_limit_page_grouped_rows() {
2962        let dir = tempdir().unwrap();
2963        let db = Db::open(dir.path(), None).unwrap();
2964        for i in 0..9 {
2965            db.put("t", &i.to_string(),
2966                serde_json::json!({"g": format!("g{}", i % 3)}), vec![], None, None).unwrap();
2967        }
2968        let (page, _) = query(
2969            &db, "FROM t GROUP BY g COUNT ORDER BY g LIMIT 1 OFFSET 1").unwrap();
2970        assert_eq!(page.len(), 1);
2971        assert_eq!(page[0]["g"], "g1");
2972    }
2973
2974    // ── HAVING ──────────────────────────────────────────────────────────────
2975
2976    #[test]
2977    fn having_filters_groups_by_count() {
2978        let dir = tempdir().unwrap();
2979        let db = Db::open(dir.path(), None).unwrap();
2980        for (i, s) in ["a", "b", "b", "b", "c", "c"].iter().enumerate() {
2981            db.put("t", &i.to_string(),
2982                serde_json::json!({"g": s, "n": i}), vec![], None, None).unwrap();
2983        }
2984        let (rows, _) = query(&db, "FROM t GROUP BY g COUNT HAVING count > 1").unwrap();
2985        let mut keys: Vec<&str> = rows.iter().map(|r| r["g"].as_str().unwrap()).collect();
2986        keys.sort();
2987        assert_eq!(keys, vec!["b", "c"], "the single-row group `a` is filtered out");
2988    }
2989
2990    #[test]
2991    fn having_filters_on_the_aggregate_value() {
2992        let (_tmp, db) = setup_items();
2993        // x sums to 15, y to 60.
2994        let (rows, _) = query(
2995            &db, "FROM items GROUP BY cat SUM price HAVING sum_price > 20").unwrap();
2996        assert_eq!(rows.len(), 1);
2997        assert_eq!(rows[0]["cat"], "y");
2998    }
2999
3000    /// HAVING gets the full predicate surface, because it runs through the
3001    /// same evaluator as WHERE rather than a second copy.
3002    #[test]
3003    fn having_supports_the_whole_predicate_surface() {
3004        let (_tmp, db) = setup_items();
3005        let (in_, _) = query(
3006            &db, r#"FROM items GROUP BY cat COUNT HAVING cat IN ("x")"#).unwrap();
3007        assert_eq!(in_.len(), 1);
3008        assert_eq!(in_[0]["cat"], "x");
3009
3010        let (btw, _) = query(
3011            &db, "FROM items GROUP BY cat SUM price HAVING sum_price BETWEEN 10 AND 20").unwrap();
3012        assert_eq!(btw.len(), 1);
3013        assert_eq!(btw[0]["cat"], "x");
3014
3015        let (like, _) = query(
3016            &db, r#"FROM items GROUP BY cat COUNT HAVING cat LIKE "y""#).unwrap();
3017        assert_eq!(like.len(), 1);
3018
3019        let (or_, _) = query(
3020            &db, "FROM items GROUP BY cat SUM price HAVING sum_price < 20 OR count = 3").unwrap();
3021        assert_eq!(or_.len(), 2);
3022    }
3023
3024    /// WHERE filters input rows, HAVING filters groups. Confusing them gives
3025    /// different answers, so the distinction must hold.
3026    #[test]
3027    fn where_and_having_are_different_stages() {
3028        let (_tmp, db) = setup_items();
3029        // WHERE drops rows BEFORE grouping, shrinking the sums.
3030        let (w, _) = query(
3031            &db, "FROM items WHERE price > 10 GROUP BY cat SUM price").unwrap();
3032        let x = w.iter().find(|r| r["cat"] == "x");
3033        assert!(x.is_none(), "x's rows (0,5,10) are all filtered out by WHERE");
3034
3035        // HAVING keeps every row in the aggregate and filters the RESULT.
3036        let (h, _) = query(
3037            &db, "FROM items GROUP BY cat SUM price HAVING sum_price > 10").unwrap();
3038        assert_eq!(h.len(), 2, "both groups sum above 10 when nothing is pre-filtered");
3039    }
3040
3041    #[test]
3042    fn having_without_an_aggregate_is_an_error() {
3043        let (_tmp, db) = setup();
3044        // HAVING is meaningless without grouping, and silently treating it as
3045        // a second WHERE would be exactly the kind of reinterpretation this
3046        // parser no longer does.
3047        assert!(query(&db, "FROM blocks HAVING height > 3").is_err());
3048    }
3049
3050    // ── Bare aggregates, no GROUP BY ────────────────────────────────────────
3051
3052    /// `FROM t COUNT` — "how many rows match?" without fetching them. The
3053    /// July engine note recorded `SELECT COUNT(*)` returning `[]` silently;
3054    /// this is the capability that was missing behind that silence.
3055    #[test]
3056    fn bare_count_returns_one_row() {
3057        let (_tmp, db) = setup();
3058        let (rows, _) = query(&db, "FROM blocks COUNT").unwrap();
3059        assert_eq!(rows.len(), 1);
3060        assert_eq!(rows[0]["count"], json!(5));
3061        assert_eq!(rows[0]["value"], json!(5));
3062    }
3063
3064    #[test]
3065    fn bare_count_respects_the_filter() {
3066        let (_tmp, db) = setup();
3067        let (rows, _) = query(&db, "FROM blocks WHERE height > 3 COUNT").unwrap();
3068        assert_eq!(rows[0]["count"], json!(2));
3069    }
3070
3071    #[test]
3072    fn bare_sum_avg_min_max() {
3073        let (_tmp, db) = setup();
3074        // heights 1..=5, n_tx = h*2 -> 2,4,6,8,10
3075        let (s, _) = query(&db, "FROM blocks SUM n_tx").unwrap();
3076        assert_eq!(s[0]["sum_n_tx"], json!(30), "integer inputs give an integer sum");
3077        let (a, _) = query(&db, "FROM blocks AVG n_tx").unwrap();
3078        assert_eq!(a[0]["avg_n_tx"], json!(6.0));
3079        let (mn, _) = query(&db, "FROM blocks MIN n_tx").unwrap();
3080        assert_eq!(mn[0]["min_n_tx"], json!(2));
3081        let (mx, _) = query(&db, "FROM blocks MAX n_tx").unwrap();
3082        assert_eq!(mx[0]["max_n_tx"], json!(10));
3083    }
3084
3085    /// Integer inputs must produce integer aggregates.
3086    ///
3087    /// Aggregating exclusively in f64 was a type divergence from the Python
3088    /// reference (which returns `66`, not `66.0`) AND a precision bug: f64
3089    /// cannot represent integers above 2^53 exactly, so a SUM over satoshi
3090    /// amounts or block heights silently rounded. This engine stores exactly
3091    /// that kind of number.
3092    #[test]
3093    fn integer_aggregates_stay_integers_and_keep_full_precision() {
3094        let dir = tempdir().unwrap();
3095        let db = Db::open(dir.path(), None).unwrap();
3096        // Beyond 2^53 (9_007_199_254_740_992), where f64 starts skipping
3097        // integers. Their true sum ends in ...9, which a f64 round-trip loses.
3098        let big: [i64; 3] = [9_007_199_254_740_993, 9_007_199_254_740_995, 1];
3099        for (i, v) in big.iter().enumerate() {
3100            db.put("t", &i.to_string(), serde_json::json!({"v": v}),
3101                   vec![], None, None).unwrap();
3102        }
3103        let (s, _) = query(&db, "FROM t SUM v").unwrap();
3104        assert_eq!(s[0]["sum_v"], json!(18_014_398_509_481_989i64),
3105                   "exact i64 sum, not a rounded f64");
3106        assert!(s[0]["sum_v"].is_i64(), "must serialise as an integer");
3107
3108        let (mx, _) = query(&db, "FROM t MAX v").unwrap();
3109        assert_eq!(mx[0]["max_v"], json!(9_007_199_254_740_995i64));
3110        let (mn, _) = query(&db, "FROM t MIN v").unwrap();
3111        assert_eq!(mn[0]["min_v"], json!(1));
3112    }
3113
3114    /// A float anywhere in the column makes the whole aggregate fractional,
3115    /// which is what Python's arithmetic does too.
3116    #[test]
3117    fn a_single_float_makes_the_aggregate_fractional() {
3118        let dir = tempdir().unwrap();
3119        let db = Db::open(dir.path(), None).unwrap();
3120        db.put("t", "1", serde_json::json!({"v": 1}), vec![], None, None).unwrap();
3121        db.put("t", "2", serde_json::json!({"v": 2.5}), vec![], None, None).unwrap();
3122        let (s, _) = query(&db, "FROM t SUM v").unwrap();
3123        assert_eq!(s[0]["sum_v"], json!(3.5));
3124        // AVG is true division, so it is fractional even over pure integers.
3125        let (a, _) = query(&db, "FROM t AVG v").unwrap();
3126        assert_eq!(a[0]["avg_v"], json!(1.75));
3127    }
3128
3129    /// A JSON bool is not a number, matching Python's explicit
3130    /// `not isinstance(x, bool)` guard.
3131    #[test]
3132    fn booleans_are_not_aggregated_as_numbers() {
3133        let dir = tempdir().unwrap();
3134        let db = Db::open(dir.path(), None).unwrap();
3135        db.put("t", "1", serde_json::json!({"v": true}), vec![], None, None).unwrap();
3136        db.put("t", "2", serde_json::json!({"v": 5}), vec![], None, None).unwrap();
3137        let (s, _) = query(&db, "FROM t SUM v").unwrap();
3138        assert_eq!(s[0]["sum_v"], json!(5), "the bool contributes nothing");
3139        assert_eq!(s[0]["count"], json!(2), "but it still counts toward the group");
3140    }
3141
3142    /// COUNT over an empty result is 0, not "no rows". A caller asking "how
3143    /// many?" must get a number.
3144    #[test]
3145    fn bare_count_of_nothing_is_zero_not_empty() {
3146        let (_tmp, db) = setup();
3147        let (rows, count) = query(&db, "FROM blocks WHERE height > 999 COUNT").unwrap();
3148        assert_eq!(count, 1, "still exactly one row");
3149        assert_eq!(rows[0]["count"], json!(0));
3150
3151        // A GROUPED aggregate over zero rows correctly has no groups.
3152        let (g, _) = query(&db, "FROM blocks WHERE height > 999 GROUP BY height COUNT").unwrap();
3153        assert!(g.is_empty());
3154    }
3155
3156    #[test]
3157    fn bare_aggregate_over_an_empty_collection() {
3158        let (_tmp, db) = setup();
3159        let (rows, _) = query(&db, "FROM nonexistent COUNT").unwrap();
3160        assert_eq!(rows[0]["count"], json!(0));
3161        let (s, _) = query(&db, "FROM nonexistent SUM n_tx").unwrap();
3162        assert_eq!(s[0]["sum_n_tx"], Value::Null, "sum of nothing is null, not 0");
3163    }
3164
3165    #[test]
3166    fn bare_aggregate_carries_no_group_key() {
3167        let (_tmp, db) = setup();
3168        let (rows, _) = query(&db, "FROM blocks COUNT").unwrap();
3169        if let Value::Object(m) = &rows[0] {
3170            let mut keys: Vec<&String> = m.keys().collect();
3171            keys.sort();
3172            assert_eq!(keys, vec!["count", "value"]);
3173        } else {
3174            panic!("expected an object");
3175        }
3176    }
3177
3178    /// A document field whose name collides with a reserved word must be
3179    /// addressable. The lexer uppercases keywords for matching, and field
3180    /// positions accept a keyword as a field name — but they used the
3181    /// UPPERCASED text, so `WHERE count > 1` searched the document for "COUNT"
3182    /// and matched nothing. Silent, and it hit real field names: count, min,
3183    /// max, sum, avg, value, search, group, order, limit, offset, trace.
3184    #[test]
3185    fn a_field_named_like_a_keyword_is_still_addressable() {
3186        let dir = tempdir().unwrap();
3187        let db = Db::open(dir.path(), None).unwrap();
3188        db.put("t", "1", serde_json::json!({
3189            "count": 5, "min": 1, "max": 9, "sum": 3, "avg": 2,
3190            "value": "keep", "limit": 7, "offset": 8, "group": "g1", "search": "s",
3191        }), vec![], None, None).unwrap();
3192        db.put("t", "2", serde_json::json!({
3193            "count": 1, "min": 0, "max": 2, "sum": 0, "avg": 0,
3194            "value": "drop", "limit": 0, "offset": 0, "group": "g2", "search": "t",
3195        }), vec![], None, None).unwrap();
3196
3197        for (nql, want) in [
3198            ("FROM t WHERE count > 3", "1"),
3199            ("FROM t WHERE min = 1", "1"),
3200            ("FROM t WHERE max >= 9", "1"),
3201            ("FROM t WHERE sum = 3", "1"),
3202            ("FROM t WHERE avg = 2", "1"),
3203            (r#"FROM t WHERE value = "keep""#, "1"),
3204            ("FROM t WHERE limit = 7", "1"),
3205            ("FROM t WHERE offset = 8", "1"),
3206            (r#"FROM t WHERE group = "g1""#, "1"),
3207        ] {
3208            let (rows, _) = query(&db, nql).unwrap();
3209            assert_eq!(rows.len(), 1, "`{}` matched {} rows", nql, rows.len());
3210            assert_eq!(rows[0]["_id"], want, "`{}`", nql);
3211        }
3212
3213        // Sorting and grouping on such a field too.
3214        let (ord, _) = query(&db, "FROM t ORDER BY count DESC").unwrap();
3215        assert_eq!(ord[0]["_id"], "1");
3216        let (grp, _) = query(&db, "FROM t GROUP BY group COUNT").unwrap();
3217        assert_eq!(grp.len(), 2);
3218        let keys: Vec<&str> = grp.iter().filter_map(|r| r["group"].as_str()).collect();
3219        assert!(keys.contains(&"g1") && keys.contains(&"g2"), "{:?}", grp);
3220    }
3221
3222    /// The raw spelling is preserved, so a mixed-case field name round-trips
3223    /// while the keyword it collides with still matches case-insensitively.
3224    #[test]
3225    fn keyword_matching_stays_case_insensitive() {
3226        let dir = tempdir().unwrap();
3227        let db = Db::open(dir.path(), None).unwrap();
3228        db.put("t", "1", serde_json::json!({"Count": 5, "n": 1}),
3229               vec![], None, None).unwrap();
3230        // Field spelled `Count`, clause keywords in lower case.
3231        let (rows, _) = query(&db, "from t where Count = 5 order by n").unwrap();
3232        assert_eq!(rows.len(), 1);
3233        // And a differently-cased field name does NOT collide with it.
3234        let (miss, _) = query(&db, "FROM t WHERE count = 5").unwrap();
3235        assert!(miss.is_empty(), "`count` and `Count` are distinct field names");
3236    }
3237
3238    #[test]
3239    fn two_aggregates_is_an_error() {
3240        let (_tmp, db) = setup();
3241        assert!(query(&db, "FROM blocks COUNT SUM n_tx").is_err());
3242        assert!(query(&db, "FROM blocks GROUP BY height COUNT SUM n_tx").is_err());
3243    }
3244
3245    #[test]
3246    fn bare_aggregate_with_having() {
3247        let (_tmp, db) = setup();
3248        let (keep, _) = query(&db, "FROM blocks COUNT HAVING count > 3").unwrap();
3249        assert_eq!(keep.len(), 1);
3250        let (drop, _) = query(&db, "FROM blocks COUNT HAVING count > 99").unwrap();
3251        assert!(drop.is_empty());
3252    }
3253
3254    // ── GROUP BY parity with the Python reference (query.py + engine.py) ────
3255
3256    /// Fixture mirroring tests/test_v050.py::test_group_by_min_max exactly:
3257    /// six items, cat x for 0..2 and y for 3..5, price = i * 5.
3258    fn setup_items() -> (tempfile::TempDir, Db) {
3259        let dir = tempdir().unwrap();
3260        let db = Db::open(dir.path(), None).unwrap();
3261        for i in 0..6 {
3262            db.put("items", &i.to_string(),
3263                serde_json::json!({"cat": if i < 3 {"x"} else {"y"}, "price": i * 5}),
3264                vec![], None, None).unwrap();
3265        }
3266        (dir, db)
3267    }
3268
3269    fn group(rows: &[Value], field: &str, key: &str) -> Value {
3270        rows.iter()
3271            .find(|r| r[field] == Value::String(key.to_string()))
3272            .unwrap_or_else(|| panic!("no group {:?} in {:?}", key, rows))
3273            .clone()
3274    }
3275
3276    /// The aggregate must read the TARGET field. Before 3.3.0 the executor
3277    /// aggregated the GROUP BY field itself and the target was silently
3278    /// dropped by the unknown-token skip, so `MAX price` returned the max of
3279    /// `cat` — a non-numeric value coerced to 1.0, making every group answer
3280    /// 1. Python returns x:0 and y:25 for MIN/MAX respectively.
3281    #[test]
3282    fn group_by_aggregates_the_target_field_not_the_group_field() {
3283        let (_tmp, db) = setup_items();
3284
3285        let (mins, _) = query(&db, "FROM items GROUP BY cat MIN price").unwrap();
3286        assert_eq!(group(&mins, "cat", "x")["min_price"], json!(0));
3287        assert_eq!(group(&mins, "cat", "y")["min_price"], json!(15));
3288
3289        let (maxs, _) = query(&db, "FROM items GROUP BY cat MAX price").unwrap();
3290        assert_eq!(group(&maxs, "cat", "y")["max_price"], json!(25));
3291        assert_eq!(group(&maxs, "cat", "x")["max_price"], json!(10));
3292
3293        let (sums, _) = query(&db, "FROM items GROUP BY cat SUM price").unwrap();
3294        assert_eq!(group(&sums, "cat", "x")["sum_price"], json!(15));  // 0+5+10
3295        assert_eq!(group(&sums, "cat", "y")["sum_price"], json!(60));  // 15+20+25
3296
3297        let (avgs, _) = query(&db, "FROM items GROUP BY cat AVG price").unwrap();
3298        assert_eq!(group(&avgs, "cat", "x")["avg_price"], json!(5.0));
3299        assert_eq!(group(&avgs, "cat", "y")["avg_price"], json!(20.0));
3300    }
3301
3302    /// An aggregate over a `_`-prefixed metadata field must see it.
3303    ///
3304    /// `_seq` lives on the node, not in its data payload, and the aggregator
3305    /// read the payload directly — so `MAX _seq` answered NULL while
3306    /// `SELECT _seq` listed the values and `WHERE _seq > 5` filtered on them.
3307    /// It was also a live divergence: the Python engine builds its groups from
3308    /// projected dicts that already carry `_seq`, and answers correctly.
3309    ///
3310    /// "What is the newest sequence?" is the question replication and time
3311    /// travel are built on, so a confident null there is the worst shape of
3312    /// wrong answer this engine can give.
3313    #[test]
3314    fn aggregates_see_node_metadata_not_only_the_payload() {
3315        let (_tmp, db) = setup_items();
3316        let (all, _) = query(&db, "FROM items").unwrap();
3317        let want = all.iter().filter_map(|r| r.get("_seq")?.as_i64()).max().unwrap();
3318
3319        let (rows, _) = query(&db, "FROM items MAX _seq").unwrap();
3320        assert_eq!(rows[0]["max__seq"], json!(want),
3321                   "MAX _seq must equal the highest sequence in the result");
3322        assert_ne!(rows[0]["max__seq"], Value::Null, "a null here is a silent wrong answer");
3323
3324        let (rows, _) = query(&db, "FROM items MIN _seq").unwrap();
3325        assert_eq!(rows[0]["min__seq"], json!(
3326            all.iter().filter_map(|r| r.get("_seq")?.as_i64()).min().unwrap()));
3327
3328        // Grouping by a metadata field works through the same resolver.
3329        let (rows, _) = query(&db, "FROM items GROUP BY _seq COUNT").unwrap();
3330        assert_eq!(rows.len(), all.len(), "one group per distinct sequence");
3331        assert!(rows.iter().all(|r| r["_seq"] != Value::Null),
3332                "the group key must be the sequence, not null");
3333    }
3334
3335    /// Output key parity: Python's engine.py emits `<agg>_<field>` and a
3336    /// `count`. This engine additionally keeps `value` as the alias it has
3337    /// always emitted, so existing callers keep working.
3338    #[test]
3339    fn group_by_emits_python_parity_keys_and_the_value_alias() {
3340        let (_tmp, db) = setup_items();
3341        let (rows, _) = query(&db, "FROM items GROUP BY cat SUM price").unwrap();
3342        let x = group(&rows, "cat", "x");
3343        assert_eq!(x["sum_price"], json!(15), "python-parity key");
3344        assert_eq!(x["value"], json!(15), "back-compat alias must agree");
3345        assert_eq!(x["count"], json!(3), "count is the group size");
3346    }
3347
3348    /// `count` is the group size; the aggregate only sees numeric targets.
3349    /// A group of 3 where one row has a non-numeric price must still report
3350    /// count=3 while averaging over 2 — matching Python's isinstance filter.
3351    #[test]
3352    fn count_is_group_size_while_aggregate_skips_non_numeric() {
3353        let dir = tempdir().unwrap();
3354        let db = Db::open(dir.path(), None).unwrap();
3355        db.put("t", "1", serde_json::json!({"g": "a", "n": 10}), vec![], None, None).unwrap();
3356        db.put("t", "2", serde_json::json!({"g": "a", "n": 20}), vec![], None, None).unwrap();
3357        db.put("t", "3", serde_json::json!({"g": "a", "n": "N/A"}), vec![], None, None).unwrap();
3358
3359        let (rows, _) = query(&db, "FROM t GROUP BY g AVG n").unwrap();
3360        let a = group(&rows, "g", "a");
3361        assert_eq!(a["count"], json!(3), "every row counts toward the group");
3362        assert_eq!(a["avg_n"], json!(15.0), "only the two numeric rows average");
3363    }
3364
3365    /// An aggregate with no numeric input is null, not 0 and not infinity.
3366    #[test]
3367    fn empty_aggregate_input_is_null() {
3368        let dir = tempdir().unwrap();
3369        let db = Db::open(dir.path(), None).unwrap();
3370        db.put("t", "1", serde_json::json!({"g": "a", "n": "x"}), vec![], None, None).unwrap();
3371        let (rows, _) = query(&db, "FROM t GROUP BY g MIN n").unwrap();
3372        assert_eq!(rows[0]["min_n"], Value::Null);
3373        assert_eq!(rows[0]["count"], json!(1));
3374    }
3375
3376    /// Python makes the aggregate keyword optional — `GROUP BY field` alone
3377    /// yields counts. Rust used to reject it as a parse error.
3378    #[test]
3379    fn bare_group_by_without_an_aggregate_counts() {
3380        let (_tmp, db) = setup_items();
3381        let (rows, _) = query(&db, "FROM items GROUP BY cat").unwrap();
3382        assert_eq!(rows.len(), 2);
3383        assert_eq!(group(&rows, "cat", "x")["count"], json!(3));
3384        assert_eq!(group(&rows, "cat", "y")["count"], json!(3));
3385    }
3386
3387    /// SUM/AVG/MIN/MAX require a target field, as in Python.
3388    #[test]
3389    fn aggregate_without_a_target_field_is_an_error() {
3390        let (_tmp, db) = setup_items();
3391        for bad in [
3392            "FROM items GROUP BY cat SUM",
3393            "FROM items GROUP BY cat AVG",
3394            "FROM items GROUP BY cat MIN",
3395        ] {
3396            assert!(query(&db, bad).is_err(), "`{}` must be rejected", bad);
3397        }
3398    }
3399
3400    /// Group output order is first-seen, so repeated runs agree. HashMap
3401    /// iteration order previously made this nondeterministic.
3402    #[test]
3403    fn group_order_is_stable_across_runs() {
3404        let (_tmp, db) = setup_items();
3405        let first = query(&db, "FROM items GROUP BY cat SUM price").unwrap().0;
3406        for _ in 0..8 {
3407            let again = query(&db, "FROM items GROUP BY cat SUM price").unwrap().0;
3408            assert_eq!(first, again);
3409        }
3410    }
3411
3412    /// GROUP BY composes with the new predicate surface.
3413    #[test]
3414    fn group_by_after_an_in_predicate() {
3415        let (_tmp, db) = setup_items();
3416        let (rows, _) = query(
3417            &db, "FROM items WHERE price IN (0, 5, 25) GROUP BY cat SUM price").unwrap();
3418        assert_eq!(group(&rows, "cat", "x")["sum_price"], json!(5));
3419        assert_eq!(group(&rows, "cat", "y")["sum_price"], json!(25));
3420    }
3421
3422    #[test]
3423    fn search() {
3424        let (_tmp, db) = setup();
3425        let (rows, _) = query(&db, r#"FROM blocks SEARCH "0003""#).unwrap();
3426        assert_eq!(rows.len(), 1);
3427    }
3428
3429    #[test]
3430    fn as_of() {
3431        let dir = tempdir().unwrap();
3432        let db = Db::open(dir.path(), None).unwrap();
3433        let v1 = db.put("docs", "x", serde_json::json!({"v": 1}), vec![], None, None).unwrap();
3434        db.put("docs", "x", serde_json::json!({"v": 2}), vec![], None, None).unwrap();
3435        let (rows, _) = query(&db, &format!("FROM docs AS OF {}", v1.seq)).unwrap();
3436        assert_eq!(rows[0]["v"], 1);
3437    }
3438
3439    #[test]
3440    fn valid_as_of() {
3441        let dir = tempdir().unwrap();
3442        let db = Db::open(dir.path(), None).unwrap();
3443        db.put("events", "e1", serde_json::json!({"type": "a"}), vec![],
3444               Some("2025-01-01".to_string()), Some("2025-06-01".to_string())).unwrap();
3445        db.put("events", "e2", serde_json::json!({"type": "b"}), vec![],
3446               Some("2026-01-01".to_string()), None).unwrap();
3447        let (rows, _) = query(&db, r#"FROM events VALID AS OF "2025-03-01""#).unwrap();
3448        assert_eq!(rows.len(), 1);
3449        assert_eq!(rows[0]["type"], "a");
3450    }
3451
3452    // ── String-literal escaping ──────────────────────────────────────────────
3453
3454    #[test]
3455    fn escaped_quote_matches_a_value_containing_a_quote() {
3456        let dir = tempdir().unwrap();
3457        let db = Db::open(dir.path(), None).unwrap();
3458        db.put("m", "q", serde_json::json!({ "name": "say \"hi\"" }), vec![], None, None)
3459            .unwrap();
3460        db.put("m", "p", serde_json::json!({ "name": "plain" }), vec![], None, None).unwrap();
3461
3462        // \" inside the literal is a literal quote; the string does not end there.
3463        let (rows, count) = query(&db, r#"FROM m WHERE name = "say \"hi\"""#).unwrap();
3464        assert_eq!(count, 1, "the escaped-quote literal matches exactly one row");
3465        assert_eq!(rows[0]["_id"], "q");
3466    }
3467
3468    #[test]
3469    fn raw_backslash_still_matches_literally() {
3470        // REGRESSION GUARD: a lone backslash stays literal, so pre-existing
3471        // backslash queries (Windows paths etc.) keep matching. This is the
3472        // property that makes the \" addition non-breaking.
3473        let dir = tempdir().unwrap();
3474        let db = Db::open(dir.path(), None).unwrap();
3475        db.put("m", "b", serde_json::json!({ "p": "back\\slash" }), vec![], None, None).unwrap();
3476
3477        let (rows, count) = query(&db, r#"FROM m WHERE p = "back\slash""#).unwrap();
3478        assert_eq!(count, 1, "a raw backslash literal matches as before");
3479        assert_eq!(rows[0]["_id"], "b");
3480    }
3481
3482    #[test]
3483    fn a_quote_can_no_longer_inject_trailing_clauses() {
3484        // The security motivation: previously a value of `x" LIMIT 1` would
3485        // terminate the literal and inject `LIMIT 1`. With \" the caller can
3486        // escape the quote so it stays part of the value and matches nothing
3487        // rogue. Here the escaped form matches the literal value verbatim.
3488        let dir = tempdir().unwrap();
3489        let db = Db::open(dir.path(), None).unwrap();
3490        db.put("m", "x", serde_json::json!({ "v": "a\"b" }), vec![], None, None).unwrap();
3491        let (rows, count) = query(&db, r#"FROM m WHERE v = "a\"b""#).unwrap();
3492        assert_eq!(count, 1);
3493        assert_eq!(rows[0]["_id"], "x");
3494    }
3495}
3496
3497#[cfg(test)]
3498mod tests_traverse {
3499    use super::*;
3500    use tempfile::tempdir;
3501    use crate::db::Db;
3502
3503    #[test]
3504    fn traverse_one_hop() {
3505        let db = Db::in_memory();
3506        db.put("driver", "d1", serde_json::json!({"name": "Bob"}),   vec![], None, None).unwrap();
3507        db.put("driver", "d2", serde_json::json!({"name": "Carol"}), vec![], None, None).unwrap();
3508        db.put("trip",   "t1", serde_json::json!({"status": "req"}), vec![], None, None).unwrap();
3509        db.put("trip",   "t2", serde_json::json!({"status": "ok"}),  vec![], None, None).unwrap();
3510
3511        db.link("driver:d1", "handles", "trip:t1").unwrap();
3512        db.link("driver:d1", "handles", "trip:t2").unwrap();
3513
3514        let (rows, count) = query(&db, r#"FROM driver WHERE _id = "d1" TRAVERSE handles"#).unwrap();
3515        assert_eq!(count, 2);
3516        let ids: std::collections::HashSet<&str> = rows.iter()
3517            .filter_map(|r| r["_id"].as_str())
3518            .collect();
3519        assert!(ids.contains("t1") && ids.contains("t2"));
3520    }
3521
3522    #[test]
3523    fn traverse_returns_empty_when_no_links() {
3524        let db = Db::in_memory();
3525        db.put("driver", "d1", serde_json::json!({"name": "Bob"}), vec![], None, None).unwrap();
3526        let (rows, count) = query(&db, r#"FROM driver WHERE _id = "d1" TRAVERSE handles"#).unwrap();
3527        assert_eq!(count, 0);
3528        assert!(rows.is_empty());
3529    }
3530
3531    #[test]
3532    fn traverse_multi_source() {
3533        // When WHERE matches multiple rows, TRAVERSE unions all their neighbors
3534        let db = Db::in_memory();
3535        db.put("driver", "d1", serde_json::json!({"status": "active"}), vec![], None, None).unwrap();
3536        db.put("driver", "d2", serde_json::json!({"status": "active"}), vec![], None, None).unwrap();
3537        db.put("trip",   "t1", serde_json::json!({"n": 1}), vec![], None, None).unwrap();
3538        db.put("trip",   "t2", serde_json::json!({"n": 2}), vec![], None, None).unwrap();
3539        db.put("trip",   "t3", serde_json::json!({"n": 3}), vec![], None, None).unwrap();
3540
3541        db.link("driver:d1", "handles", "trip:t1").unwrap();
3542        db.link("driver:d1", "handles", "trip:t2").unwrap();
3543        db.link("driver:d2", "handles", "trip:t3").unwrap();
3544
3545        let (_rows, count) = query(&db, r#"FROM driver WHERE status = "active" TRAVERSE handles"#).unwrap();
3546        assert_eq!(count, 3);
3547    }
3548
3549    #[test]
3550    fn traverse_nql_keyword_case_insensitive() {
3551        // Parser normalises to uppercase — "traverse" and "TRAVERSE" both work
3552        let db = Db::in_memory();
3553        db.put("driver", "d1", serde_json::json!({}), vec![], None, None).unwrap();
3554        db.put("trip",   "t1", serde_json::json!({}), vec![], None, None).unwrap();
3555        db.link("driver:d1", "handles", "trip:t1").unwrap();
3556        // uppercase
3557        let (r1, c1) = query(&db, r#"FROM driver WHERE _id = "d1" TRAVERSE handles"#).unwrap();
3558        assert_eq!(c1, 1);
3559        // lowercase (lexer uppercases keywords)
3560        let (r2, c2) = query(&db, r#"FROM driver WHERE _id = "d1" traverse handles"#).unwrap();
3561        assert_eq!(c2, 1);
3562        assert_eq!(r1[0]["_id"], r2[0]["_id"]);
3563    }
3564
3565    #[test]
3566    fn traverse_durable() {
3567        let dir = tempdir().unwrap();
3568        {
3569            let db = Db::open(dir.path(), None).unwrap();
3570            db.put("driver", "d1", serde_json::json!({"name": "Bob"}),   vec![], None, None).unwrap();
3571            db.put("trip",   "t1", serde_json::json!({"status": "req"}), vec![], None, None).unwrap();
3572            db.link("driver:d1", "handles", "trip:t1").unwrap();
3573        }
3574        let db2 = Db::open(dir.path(), None).unwrap();
3575        db2.startup_ready.store(true, std::sync::atomic::Ordering::SeqCst);
3576        let (rows, count) = query(&db2, r#"FROM driver WHERE _id = "d1" TRAVERSE handles"#).unwrap();
3577        assert_eq!(count, 1);
3578        assert_eq!(rows[0]["_id"], "t1");
3579    }
3580}