Skip to main content

quarb_sql/
export.rs

1//! The reverse direction: Quarb → SQL.
2//!
3//! Walks the query's *reflection arbor* — the locked vocabulary is
4//! the stable surface for query-rewriting tooling — and emits an
5//! equivalent `SELECT` statement, refusing what the SQL query core
6//! cannot express. Fragments and pure macros expand before
7//! reflection, so they translate for free.
8//!
9//! The translatable subset mirrors the importer: `/table/*`
10//! branches with predicates (→ `WHERE`), witness joins (`<=>` with
11//! `$*1` equality → `JOIN ... ON`, remaining conditions → `WHERE`,
12//! `$*k` select fields qualified), `rec(...)` select lists,
13//! whole-table and grouped aggregates (`GROUP BY`, a filter after
14//! the reduction → `HAVING`), `sort_by`/`reverse`/`top` →
15//! `ORDER BY`/`LIMIT`, `@| [..n]` → `LIMIT`, and single-column
16//! `unique` → `DISTINCT`.
17//!
18//! Deliberately refused: `-->` resolution chains — the foreign-key
19//! targets live in the *schema*, not the query text, so a chain
20//! cannot be compiled to a join without a database at hand; spell
21//! the join explicitly with `<=>` to export it. Also refused:
22//! registers beyond the grouped-aggregate pattern, windows,
23//! captures, and regex matching (`LIKE` dialects disagree).
24//!
25//! Notes carry the standing divergences: truthiness (`[::c]` →
26//! `IS NOT NULL`, but Quarb also treats `0` and `''` as falsy),
27//! `*=` → `LIKE` case-folding dialects, and join cardinality
28//! (Quarb's existential binding never multiplies rows; SQL `JOIN`
29//! does when several left rows match).
30
31use crate::{SqlError, Translation};
32use quarb::reflect::QueryArbor;
33use quarb::{AstAdapter, NodeId, Value};
34
35/// Translate a Quarb query to a SQL `SELECT` statement.
36pub fn export(quarb: &str) -> Result<Translation, SqlError> {
37    refuse_marker(quarb)?;
38    let arbor =
39        QueryArbor::parse(quarb).map_err(|e| SqlError::Syntax(format!("parsing Quarb: {e}")))?;
40    refuse_groups(&arbor)?;
41    let mut ex = Exporter {
42        arbor,
43        notes: Vec::new(),
44        strict: false,
45        dialect: None,
46        from_table: String::new(),
47        join_on_cols: Vec::new(),
48        join_table: None,
49        join_every: false,
50        column_types: ColumnTypes::default(),
51        from_sql: String::new(),
52        join_sql: None,
53        in_on: false,
54        aggregate: false,
55        keyed_hops: false,
56    };
57    let query = ex.query()?;
58    Ok(Translation {
59        query,
60        notes: ex.notes,
61    })
62}
63
64/// The exporter rewrites `__LEFT__` (the join's left table) and
65/// `__AGG__` (the HAVING aggregate) as internal placeholders.
66/// Query text containing either marker would be rewritten inside
67/// its own string literals — and could spoof the emitted SQL — so
68/// such queries stay on the scan path.
69fn refuse_marker(quarb: &str) -> Result<(), SqlError> {
70    for marker in ["__LEFT__", "__AGG__"] {
71        if quarb.contains(marker) {
72            return Err(SqlError::Unsupported(format!(
73                "query text contains the reserved marker \"{marker}\""
74            )));
75        }
76    }
77    Ok(())
78}
79
80/// A pushdown plan: SQL whose execution is provably identical to
81/// the Quarb query's — plus the table whose primary key must order
82/// the rows (`None` for a single aggregate row, where order is
83/// moot). The driver appends the `ORDER BY`, since the key lives in
84/// its catalog.
85pub struct Pushdown {
86    pub sql: String,
87    pub order_table: Option<String>,
88    /// Present when the plan contains a witness JOIN: the joined
89    /// table and the columns its ON equalities bind on it
90    /// (collected structurally from the arbor, so query text
91    /// cannot spoof them).
92    /// The plan is only sound if those columns form a unique key
93    /// of the joined table — each FROM row must find at most one
94    /// witness, else SQL multiplies rows where Quarb's existential
95    /// binding does not. The *driver* must verify against its
96    /// catalog before executing, and fall back to the scan if it
97    /// cannot.
98    pub join_left: Option<(String, Vec<String>)>,
99    /// Present when the plan is an every-witness JOIN (`<=>*`,
100    /// ruling 2026-11-11): the joined table. Such a JOIN is what the
101    /// query asks, so it carries no uniqueness obligation
102    /// (`join_left` is absent); its obligation is the ORDER: the
103    /// rows of one driver stand in the joined table's own order,
104    /// after the driver's (`order_table`'s key, then this table's).
105    /// A driver that cannot order by both must decline the plan.
106    pub order_then: Option<String>,
107    /// What the plan takes for granted about column types. Quarb
108    /// compares by value (a numeric-looking text and a number meet
109    /// as numbers, a number and other text never meet); SQL
110    /// compares by the column's type, and the loosely typed engines
111    /// (SQLite, MySQL) coerce by rules of their own. The plan is
112    /// the scan's only where the columns it compares with a number
113    /// are numeric-typed and those it compares with text are not:
114    /// the caller asks its catalog and scans when one is otherwise.
115    /// (A strictly typed engine rejects the mismatch itself, which
116    /// sends the caller to the scan as well.)
117    pub column_types: ColumnTypes,
118    /// The tables the plan reads (the FROM table, then a joined one).
119    pub tables: Vec<String>,
120}
121
122/// The column types a pushed plan assumes (see
123/// [`Pushdown::column_types`]).
124#[derive(Clone, Debug, Default, PartialEq, Eq)]
125pub struct ColumnTypes {
126    /// Columns compared with a numeric literal.
127    pub numeric: Vec<String>,
128    /// Columns compared with a text literal.
129    pub text: Vec<String>,
130    /// Columns the plan extracts a JSON path from on the strength
131    /// of the column's declaration alone (the hop carried no
132    /// `<json>`): the pushed `json_extract` is the scan's only where
133    /// the catalog declares the column json, since the scan grafts
134    /// a leaf only as declared (spec: Grafting).
135    pub json: Vec<String>,
136}
137
138impl ColumnTypes {
139    pub fn is_empty(&self) -> bool {
140        self.numeric.is_empty() && self.text.is_empty() && self.json.is_empty()
141    }
142
143    /// The assumptions a catalog does not bear out: the columns
144    /// compared with a number that are not numeric-typed, and those
145    /// compared with text that are. `catalog` lists every column of
146    /// the tables read, with whether its type is numeric and
147    /// whether it is declared json; names meet without regard to
148    /// case. A column the catalog does not list is unknown, and
149    /// counts as unmet.
150    pub fn unmet(&self, catalog: &[(String, bool, bool)]) -> Vec<String> {
151        let met = |column: &str, pick: fn(&(String, bool, bool)) -> bool, want: bool| {
152            let mut found = catalog
153                .iter()
154                .filter(|(name, ..)| name.eq_ignore_ascii_case(column))
155                .peekable();
156            found.peek().is_some() && found.all(|entry| pick(entry) == want)
157        };
158        let numeric = |e: &(String, bool, bool)| e.1;
159        let json = |e: &(String, bool, bool)| e.2;
160        let mut out: Vec<String> = Vec::new();
161        for (columns, pick, want) in [
162            (
163                &self.numeric,
164                numeric as fn(&(String, bool, bool)) -> bool,
165                true,
166            ),
167            (&self.text, numeric, false),
168            (&self.json, json, true),
169        ] {
170            for c in columns {
171                if !met(c, pick, want) && !out.contains(c) {
172                    out.push(c.clone());
173                }
174            }
175        }
176        out
177    }
178}
179
180/// The target SQL dialect, for the one construct whose emitted
181/// SQL is not portable: a filter that navigates *into* a JSON
182/// column, which each engine extracts with its own operator.
183/// The rest of a pushdown is dialect-agnostic. A query with no
184/// JSON-column filter emits identical SQL regardless of dialect.
185#[derive(Clone, Copy, PartialEq, Eq, Debug)]
186pub enum Dialect {
187    Postgres,
188    MySql,
189    Sqlite,
190    Mssql,
191    Oracle,
192}
193
194/// Attempt the pushdown translation: `Some` only when every
195/// construct in the query is in the verified-safe set. Anything
196/// else — including everything `export` would merely annotate with
197/// a divergence note — returns `None`, and the caller scans.
198///
199/// `dialect` enables JSON-column-path pushdown for that engine
200/// (fixed-path string equality only); `None` keeps such filters
201/// on the client-side graft.
202pub fn pushdown(quarb: &str, dialect: Option<Dialect>) -> Option<Pushdown> {
203    pushdown_explained(quarb, dialect).ok()
204}
205
206/// [`pushdown`], keeping the refusal: the error names the first
207/// construct that kept the query on the scan path.
208pub fn pushdown_explained(quarb: &str, dialect: Option<Dialect>) -> Result<Pushdown, SqlError> {
209    refuse_marker(quarb)?;
210    let arbor =
211        QueryArbor::parse(quarb).map_err(|e| SqlError::Syntax(format!("parsing Quarb: {e}")))?;
212    refuse_groups(&arbor)?;
213    let mut ex = Exporter {
214        arbor,
215        notes: Vec::new(),
216        strict: true,
217        dialect,
218        from_table: String::new(),
219        join_on_cols: Vec::new(),
220        join_table: None,
221        join_every: false,
222        column_types: ColumnTypes::default(),
223        from_sql: String::new(),
224        join_sql: None,
225        in_on: false,
226        aggregate: false,
227        keyed_hops: false,
228    };
229    let sql = ex.query()?;
230    let order_table = if ex.aggregate {
231        None
232    } else {
233        // Rows come back in the driver's document order — the FROM
234        // table's (driver-first correlation).
235        Some(ex.from_table.clone())
236    };
237    // an every-witness JOIN multiplies rows by design: no uniqueness
238    // to verify, the joined table's order to keep instead
239    let join_left = if ex.join_every {
240        None
241    } else {
242        ex.join_table.clone().map(|t| (t, ex.join_on_cols.clone()))
243    };
244    let order_then = if ex.join_every && !ex.aggregate {
245        ex.join_table.clone()
246    } else {
247        None
248    };
249    let mut tables = vec![ex.from_table.clone()];
250    tables.extend(ex.join_table.clone());
251    Ok(Pushdown {
252        sql,
253        order_table,
254        join_left,
255        order_then,
256        column_types: ex.column_types.clone(),
257        tables,
258    })
259}
260
261/// The dialect-specific SQL that extracts a JSON scalar at a
262/// fixed object path, unquoted to text. `path` holds plain
263/// object keys (identifier-safe, per `json_path`), so no
264/// per-dialect path-escaping is needed. Each engine's operator
265/// returns the value as text and yields NULL for an absent path
266/// or a non-scalar — matching the graft, which excludes those
267/// rows too.
268fn json_extract(dialect: Dialect, qual: Option<&str>, col: &str, path: &[String]) -> String {
269    let qcol = match qual {
270        Some(q) => format!("{q}.{col}"),
271        None => col.to_string(),
272    };
273    match dialect {
274        // `#>>` takes a text-array path and returns text; the
275        // `::jsonb` cast lets it work on json, jsonb, and
276        // text-holding-JSON columns alike (an invalid-JSON row
277        // errors, and the driver falls back to the scan).
278        Dialect::Postgres => format!("({qcol}::jsonb #>> '{{{}}}')", path.join(",")),
279        // JSON_UNQUOTE(JSON_EXTRACT(...)) is the `->>` shorthand
280        // spelled out — portable across MySQL and MariaDB, where
281        // the `->>` operator itself is not.
282        Dialect::MySql => {
283            format!("JSON_UNQUOTE(JSON_EXTRACT({qcol}, '$.{}'))", path.join("."))
284        }
285        Dialect::Sqlite => format!("json_extract({qcol}, '$.{}')", path.join(".")),
286        // JSON_VALUE returns a scalar as text (lax mode: NULL on a
287        // missing path or a non-scalar, no error).
288        Dialect::Mssql | Dialect::Oracle => format!("JSON_VALUE({qcol}, '$.{}')", path.join(".")),
289    }
290}
291
292/// Wrap a JSON-path condition in the dialect's validity guard,
293/// where a cheap one exists. SQLite and MySQL error the whole
294/// statement on one malformed-JSON row — which turned every
295/// pushdown over a dirty table into a silent fallback scan — and
296/// the graft excludes such rows anyway (no parse, no subtree), so
297/// the guard is observationally identical. SQL Server gets ISJSON;
298/// Oracle's JSON_VALUE is lax already; PostgreSQL has no guard
299/// short of the ::jsonb cast itself (an invalid row errors and the
300/// caller falls back to the scan).
301fn json_valid_guard(dialect: Dialect, qual: Option<&str>, col: &str, cond: String) -> String {
302    let qcol = match qual {
303        Some(q) => format!("{q}.{col}"),
304        None => col.to_string(),
305    };
306    match dialect {
307        Dialect::Sqlite => format!("(json_valid({qcol}) AND {cond})"),
308        Dialect::MySql => format!("(JSON_VALID({qcol}) AND {cond})"),
309        Dialect::Mssql => format!("(ISJSON({qcol}) = 1 AND {cond})"),
310        Dialect::Postgres | Dialect::Oracle => format!("({cond})"),
311    }
312}
313
314/// The dialect's JSON type probe at a fixed path — non-NULL iff
315/// the path exists. A JSON `null` value reports its type ('null'),
316/// so existence still sees it, matching the graft, where a
317/// null-valued key is a node. Only the dialects with a native
318/// probe participate.
319fn json_type_probe(
320    dialect: Dialect,
321    qual: Option<&str>,
322    col: &str,
323    path: &[String],
324) -> Option<String> {
325    let qcol = match qual {
326        Some(q) => format!("{q}.{col}"),
327        None => col.to_string(),
328    };
329    match dialect {
330        Dialect::Sqlite => Some(format!("json_type({qcol}, '$.{}')", path.join("."))),
331        Dialect::Postgres => Some(format!(
332            "jsonb_typeof({qcol}::jsonb #> '{{{}}}')",
333            path.join(",")
334        )),
335        Dialect::MySql | Dialect::Mssql | Dialect::Oracle => None,
336    }
337}
338
339/// Flip a comparison for a swapped operand order (`lit OP path` →
340/// `path OP' lit`).
341fn flip_op(op: &str) -> String {
342    match op {
343        "<" => ">".into(),
344        "<=" => ">=".into(),
345        ">" => "<".into(),
346        ">=" => "<=".into(),
347        other => other.into(),
348    }
349}
350
351/// SQL keywords that must not appear as a bare identifier or `AS`
352/// alias — quoting them portably differs by dialect, so strict
353/// mode refuses and export mode quotes with double quotes plus a
354/// note.
355const SQL_KEYWORDS: &[&str] = &[
356    "all",
357    "and",
358    "as",
359    "asc",
360    "by",
361    "case",
362    "cross",
363    "desc",
364    "distinct",
365    "else",
366    "end",
367    "except",
368    "exists",
369    "from",
370    "group",
371    "having",
372    "in",
373    "index",
374    "inner",
375    "intersect",
376    "into",
377    "is",
378    "join",
379    "left",
380    "like",
381    "limit",
382    "not",
383    "null",
384    "offset",
385    "on",
386    "or",
387    "order",
388    "outer",
389    "right",
390    "select",
391    "set",
392    "table",
393    "then",
394    "union",
395    "unique",
396    "update",
397    "using",
398    "values",
399    "when",
400    "where",
401];
402
403/// A bare SQL identifier, portable across the target dialects: a
404/// letter or underscore, then letters, digits, and underscores,
405/// and not a reserved word.
406fn is_plain_ident(name: &str) -> bool {
407    !name.is_empty()
408        && name
409            .chars()
410            .next()
411            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
412        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
413        && !SQL_KEYWORDS.contains(&name.to_ascii_lowercase().as_str())
414}
415
416/// The SELECT under construction.
417#[derive(Default)]
418struct Select {
419    select: Vec<String>,
420    distinct: bool,
421    from: String,
422    join: Option<(String, String)>, // (table, ON condition)
423    /// The join keeps every FROM row (`<=>?`, the outer
424    /// correlation): a LEFT JOIN.
425    join_outer: bool,
426    wheres: Vec<String>,
427    group_by: Option<String>,
428    having: Option<String>,
429    order_by: Option<(String, bool)>, // (expr, desc)
430    limit: Option<String>,
431}
432
433impl Select {
434    fn render(&self) -> String {
435        let mut out = String::from("SELECT ");
436        if self.distinct {
437            out.push_str("DISTINCT ");
438        }
439        if self.select.is_empty() {
440            out.push('*');
441        } else {
442            out.push_str(&self.select.join(", "));
443        }
444        out.push_str(&format!(" FROM {}", self.from));
445        if let Some((t, on)) = &self.join {
446            let kind = if self.join_outer { "LEFT JOIN" } else { "JOIN" };
447            out.push_str(&format!(" {kind} {t} ON {on}"));
448        }
449        if !self.wheres.is_empty() {
450            out.push_str(&format!(" WHERE {}", self.wheres.join(" AND ")));
451        }
452        if let Some(g) = &self.group_by {
453            out.push_str(&format!(" GROUP BY {g}"));
454        }
455        if let Some(h) = &self.having {
456            out.push_str(&format!(" HAVING {h}"));
457        }
458        if let Some((e, desc)) = &self.order_by {
459            out.push_str(&format!(" ORDER BY {e}"));
460            if *desc {
461                out.push_str(" DESC");
462            }
463        }
464        if let Some(n) = &self.limit {
465            out.push_str(&format!(" LIMIT {n}"));
466        }
467        out
468    }
469}
470
471/// A partial-pushdown plan: the leading row predicates as a WHERE
472/// clause for `table`'s fetch. The caller runs the *original* query
473/// against the filtered adapter — the engine re-applies the pushed
474/// predicates (a no-op on pre-filtered rows), so no rewriting.
475pub struct Partial {
476    pub table: String,
477    pub where_sql: String,
478    /// As [`Pushdown::column_types`]: the prefilter keeps every row
479    /// the scan would only where these assumptions hold.
480    pub column_types: ColumnTypes,
481}
482
483/// Attempt a partial pushdown: `Some` when the query's leading row
484/// predicates translate strictly and the rest of the query provably
485/// cannot observe the filtering. The gates, each with its reason:
486/// a single `/table/*` branch with no correlations (other shapes
487/// address other data); only the *leading* run of expression
488/// predicates pushes (a positional predicate before an expression
489/// one sees unfiltered rows on the scan path); the table's name
490/// appears exactly once among the query's steps (a second reach —
491/// `^`-anchored subcontexts, self-references — would see the
492/// filtered subset); no crosslink or resolution axes anywhere
493/// (backlinks and reverse resolution into the table would too);
494/// and no `:` / `:::` metadata anywhere (a filtered `:::n-rows`
495/// would lie).
496pub fn partial_pushdown(quarb: &str, dialect: Option<Dialect>) -> Option<Partial> {
497    partial_pushdown_explained(quarb, dialect).ok()
498}
499
500/// [`partial_pushdown`], keeping the refusal reason. `dialect`
501/// enables the JSON-column prefilters — the strict fixed-path
502/// string equality, plus the relaxed superset forms (numeric
503/// comparisons, existence) that are safe here and only here,
504/// because the caller re-runs the original query over the
505/// fetched subset.
506pub fn partial_pushdown_explained(
507    quarb: &str,
508    dialect: Option<Dialect>,
509) -> Result<Partial, SqlError> {
510    partial_pushdown_with(quarb, dialect, false)
511}
512
513/// [`partial_pushdown_explained`] for an adapter that reads hops by
514/// key and filters only the table's listing
515/// (`RelationalModel::with_filtered_listing`): crosslinks and
516/// resolutions no longer refuse the prefilter, since a hop into the
517/// filtered table reads its row unfiltered. What still refuses: a
518/// second navigation into the table, and a `<--` or `=>` scope that
519/// could list it.
520pub fn partial_pushdown_keyed(quarb: &str, dialect: Option<Dialect>) -> Result<Partial, SqlError> {
521    partial_pushdown_with(quarb, dialect, true)
522}
523
524fn partial_pushdown_with(
525    quarb: &str,
526    dialect: Option<Dialect>,
527    keyed_hops: bool,
528) -> Result<Partial, SqlError> {
529    refuse_marker(quarb)?;
530    let arbor =
531        QueryArbor::parse(quarb).map_err(|e| SqlError::Syntax(format!("parsing Quarb: {e}")))?;
532    refuse_groups(&arbor)?;
533    let mut ex = Exporter {
534        arbor,
535        notes: Vec::new(),
536        strict: true,
537        dialect,
538        from_table: String::new(),
539        join_on_cols: Vec::new(),
540        join_table: None,
541        join_every: false,
542        column_types: ColumnTypes::default(),
543        from_sql: String::new(),
544        join_sql: None,
545        in_on: false,
546        aggregate: false,
547        keyed_hops,
548    };
549    ex.partial()
550}
551
552/// Refuse a query carrying path-pattern groups: neither the SQL
553/// translation nor the pushdown safe set covers them, and the shape
554/// checks below count only `step` children — an unguarded group
555/// would silently vanish from the translation. Refused queries fall
556/// back to the scan path, which evaluates groups correctly.
557fn refuse_groups(arbor: &QueryArbor) -> Result<(), SqlError> {
558    let mut stack = vec![arbor.root()];
559    while let Some(n) = stack.pop() {
560        if arbor.name(n).as_deref() == Some("group") {
561            return Err(SqlError::Unsupported(
562                "path patterns (groups and quantifiers)".into(),
563            ));
564        }
565        stack.extend(arbor.children(n));
566    }
567    Ok(())
568}
569
570struct Exporter {
571    arbor: QueryArbor,
572    notes: Vec<String>,
573    /// Pushdown mode: refuse every construct whose SQL semantics
574    /// are not provably identical to Quarb's (LIKE case folding,
575    /// truthiness, group/distinct/sort ordering).
576    strict: bool,
577    /// The target dialect for JSON-column-path pushdown; `None`
578    /// leaves such filters on the client-side graft.
579    dialect: Option<Dialect>,
580    from_table: String,
581    join_on_cols: Vec<String>,
582    join_table: Option<String>,
583    /// The correlation is `<=>*`: every witness, the SQL JOIN itself.
584    join_every: bool,
585    /// What the comparisons assume of column types (see
586    /// [`Pushdown::column_types`]).
587    column_types: ColumnTypes,
588    from_sql: String,
589    join_sql: Option<String>,
590    in_on: bool,
591    aggregate: bool,
592    /// The adapter reads hops by key (the pushed-down WHERE filters
593    /// the table's listing only), so crosslinks and resolutions are
594    /// safe beside the prefilter.
595    keyed_hops: bool,
596}
597
598impl Exporter {
599    fn kids(&self, n: NodeId, kind: &str) -> Vec<NodeId> {
600        self.arbor
601            .children(n)
602            .into_iter()
603            .filter(|&c| self.arbor.name(c).as_deref() == Some(kind))
604            .collect()
605    }
606
607    fn kid(&self, n: NodeId, kind: &str) -> Option<NodeId> {
608        self.kids(n, kind).into_iter().next()
609    }
610
611    fn prop(&self, n: NodeId, key: &str) -> Option<Value> {
612        self.arbor.property(n, key)
613    }
614
615    fn prop_s(&self, n: NodeId, key: &str) -> String {
616        self.prop(n, key).map(|v| v.to_string()).unwrap_or_default()
617    }
618
619    fn kind(&self, n: NodeId) -> String {
620        self.arbor.name(n).unwrap_or_default()
621    }
622
623    /// Whether `n` is a bare `null` literal operand.
624    fn is_null_literal(&self, n: NodeId) -> bool {
625        self.kind(n) == "literal" && self.prop_s(n, "type") == "null"
626    }
627
628    /// The partial-pushdown analysis (see [`partial_pushdown`]).
629    fn partial(&mut self) -> Result<Partial, SqlError> {
630        let root = self.arbor.root();
631        let q = self
632            .kid(root, "query")
633            .ok_or_else(|| SqlError::Unsupported("empty query".into()))?;
634        // A correlation does not forbid the prefilter: the driver's
635        // own predicates restrict the driver's rows whatever the join
636        // then binds. What must not happen is the join (or anything
637        // else) reaching the filtered table a second time — a
638        // self-join would see only the filtered rows — and the
639        // whole-query gates below refuse exactly that: they walk the
640        // correlation entries too.
641        let branches = self.kids(q, "branch");
642        if branches.len() != 1 {
643            return Err(SqlError::Unsupported("a branch union".into()));
644        }
645        let (table, preds) = self.table_branch_lead(branches[0], self.keyed_hops)?;
646
647        // Whole-query gates.
648        let all = self.walk_all(root);
649        let mut table_mentions = 0;
650        for n in &all {
651            match self.kind(*n).as_str() {
652                "step" => {
653                    let axis = self.prop_s(*n, "axis");
654                    // A crosslink, a resolution or a value match may
655                    // land in (or search) the filtered table and would
656                    // see only its filtered rows: `=>` and the scoped
657                    // `<--` carry their scope as text, so the table
658                    // count below cannot see them.
659                    if matches!(axis.as_str(), "->" | "<-" | "--" | "-->" | "<--" | "=>") {
660                        // Where hops are read by key they are exact
661                        // beside the prefilter. A scope is a listing,
662                        // though: it is safe only when it plainly
663                        // lists another table (`/other/…`), and an
664                        // unscoped `=>` walks every table.
665                        let scope = self.prop_s(*n, "scope");
666                        let lists_other_table = scope
667                            .strip_prefix('/')
668                            .and_then(|rest| rest.split(['/', '[', '<']).next())
669                            .is_some_and(|first| {
670                                !first.is_empty()
671                                    && first != table
672                                    && first.chars().all(|c| c.is_alphanumeric() || c == '_')
673                            });
674                        let safe = self.keyed_hops
675                            && if scope.is_empty() {
676                                axis != "=>"
677                            } else {
678                                lists_other_table
679                            };
680                        if !safe {
681                            return Err(SqlError::Unsupported(
682                                "crosslink/resolution axes could reach \
683                                 the filtered table"
684                                    .into(),
685                            ));
686                        }
687                    }
688                    if self.prop_s(*n, "matcher") == table {
689                        table_mentions += 1;
690                    }
691                }
692                "projection" if self.prop_s(*n, "kind") != "property" => {
693                    return Err(SqlError::Unsupported(
694                        "metadata would observe the filtering \
695                         (:::n-rows, :index)"
696                            .into(),
697                    ));
698                }
699                _ => {}
700            }
701        }
702        if table_mentions != 1 {
703            return Err(SqlError::Unsupported(
704                "the table is reached more than once".into(),
705            ));
706        }
707
708        // The leading run of expression predicates. Strict
709        // translation first; a predicate the strict translator
710        // refuses tries the relaxed prefilter ladder — superset
711        // semantics: the fetched set may hold extra rows, because
712        // the caller re-runs the ORIGINAL query, which re-applies
713        // every predicate; it must never lose a matching row. An
714        // untranslatable predicate is skipped, not fatal — a
715        // shorter conjunction is still a superset filter. A
716        // positional predicate (index/range) ends the run:
717        // predicates after it filter a positionally-selected
718        // subsequence.
719        let mut conds = Vec::new();
720        for p in preds {
721            if self.prop_s(p, "kind") != "expr" {
722                break;
723            }
724            match self.predicate_cond(p, None) {
725                Ok(c) => conds.push(c),
726                Err(_) => {
727                    if let Some(c) = self.prefilter_cond(p) {
728                        conds.push(c);
729                    }
730                }
731            }
732        }
733        if conds.is_empty() {
734            return Err(SqlError::Unsupported(
735                "no leading expression predicates to push".into(),
736            ));
737        }
738        Ok(Partial {
739            table,
740            where_sql: conds.join(" AND "),
741            column_types: self.column_types.clone(),
742        })
743    }
744
745    /// The relaxed prefilter for one refused expression predicate:
746    /// the AND of whatever conjuncts translate, each a superset of
747    /// the rows its Quarb counterpart keeps. None when nothing
748    /// does — the predicate stays entirely on the engine.
749    fn prefilter_cond(&mut self, p: NodeId) -> Option<String> {
750        let parts: Vec<String> = self
751            .arbor
752            .children(p)
753            .into_iter()
754            .filter_map(|c| {
755                self.pred_expr(c, None)
756                    .ok()
757                    .or_else(|| self.prefilter_expr(c))
758            })
759            .collect();
760        if parts.is_empty() {
761            None
762        } else {
763            Some(parts.join(" AND "))
764        }
765    }
766
767    /// One conjunct's superset prefilter — fixed-path JSON shapes
768    /// only, per dialect. Every form here is proven to keep every
769    /// row the graft would match (extras are fine; the engine
770    /// re-checks). The proofs lean on three graft facts: absent
771    /// paths match no comparison; `value_eq`/`value_cmp` coerce
772    /// numeric-looking strings numerically; and Str-to-Str
773    /// ordering is bytewise.
774    fn prefilter_expr(&mut self, e: NodeId) -> Option<String> {
775        let dialect = self.dialect?;
776        match self.kind(e).as_str() {
777            // A bare truthy path: existence (with `::`, value
778            // truthiness — existence is its superset). The type
779            // probe sees JSON null too, as the graft does.
780            "path" => {
781                let (col, path) = self.json_path_loose(e)?;
782                self.note_json_column(e, &col);
783                let probe = json_type_probe(dialect, None, &col, &path)?;
784                Some(json_valid_guard(
785                    dialect,
786                    None,
787                    &col,
788                    format!("{probe} IS NOT NULL"),
789                ))
790            }
791            "compare" => {
792                let op = self.prop_s(e, "op");
793                let kids = self.arbor.children(e);
794                if kids.len() != 2 {
795                    return None;
796                }
797                for (pi, li) in [(0usize, 1usize), (1, 0)] {
798                    let Some((col, path)) = self.json_path(kids[pi]) else {
799                        continue;
800                    };
801                    if self.kind(kids[li]) != "literal" {
802                        continue;
803                    }
804                    let ty = self.prop_s(kids[li], "type");
805                    if ty == "null" {
806                        return None;
807                    }
808                    let raw = self
809                        .prop(kids[li], "value")
810                        .map(|v| v.to_string())
811                        .unwrap_or_default();
812                    let op = if pi == 0 { op.clone() } else { flip_op(&op) };
813                    self.note_json_column(kids[pi], &col);
814                    return self.json_prefilter(dialect, &col, &path, &op, &ty, &raw);
815                }
816                None
817            }
818            _ => None,
819        }
820    }
821
822    /// Build the dialect's superset prefilter for
823    /// `json_path OP literal`.
824    fn json_prefilter(
825        &self,
826        d: Dialect,
827        col: &str,
828        path: &[String],
829        op: &str,
830        lit_ty: &str,
831        raw: &str,
832    ) -> Option<String> {
833        if !matches!(op, "=" | "!=" | "<" | "<=" | ">" | ">=") {
834            return None;
835        }
836        // `!=` matches every present path whose value isn't the
837        // literal — including JSON null and cross-typed values —
838        // so its floor is existence.
839        if op == "!=" {
840            let probe = json_type_probe(d, None, col, path)?;
841            return Some(json_valid_guard(
842                d,
843                None,
844                col,
845                format!("{probe} IS NOT NULL"),
846            ));
847        }
848        let numeric_lit = raw.trim().parse::<f64>().is_ok_and(|f| f.is_finite())
849            && (lit_ty != "text" || !raw.trim().is_empty());
850        if numeric_lit {
851            let num: f64 = raw.trim().parse().ok()?;
852            // Past 2^53 the engines' exact integers and the
853            // graft's f64 part ways at the boundary.
854            if num.abs() >= 9_007_199_254_740_992.0 {
855                return None;
856            }
857            let lit = raw.trim();
858            match d {
859                // Typed extract: JSON numbers compare numerically
860                // (both sides parse the same source text to f64);
861                // string values escape through the type probe —
862                // the graft may coerce them, the server must not
863                // drop them.
864                Dialect::Sqlite => {
865                    let ex = json_extract(d, None, col, path);
866                    let ty = json_type_probe(d, None, col, path)?;
867                    Some(json_valid_guard(
868                        d,
869                        None,
870                        col,
871                        format!("({ex} {op} {lit} OR {ty} = 'text')"),
872                    ))
873                }
874                // float8 is the graft's f64; jsonb numbers print
875                // exactly, so the cast parses the same decimal.
876                // Strings escape; everything else can't match.
877                Dialect::Postgres => {
878                    let text = json_extract(d, None, col, path);
879                    let ty = json_type_probe(d, None, col, path)?;
880                    Some(format!(
881                        "(CASE WHEN {ty} = 'number' THEN ({text})::float8 {op} {lit} \
882                         WHEN {ty} = 'string' THEN true ELSE false END)"
883                    ))
884                }
885                Dialect::MySql | Dialect::Mssql | Dialect::Oracle => None,
886            }
887        } else if lit_ty == "text" {
888            if raw.contains('\'') || raw.contains('\\') {
889                return None;
890            }
891            match d {
892                // Typed extract again: string values order bytewise
893                // on both sides; numbers and booleans sit below
894                // text in SQLite's cross-type order, so `<` keeps
895                // them (extras, re-checked) and `>` drops them
896                // (the graft refuses to order Str against them).
897                Dialect::Sqlite => {
898                    let ex = json_extract(d, None, col, path);
899                    Some(json_valid_guard(d, None, col, format!("{ex} {op} '{raw}'")))
900                }
901                // Text ordering elsewhere runs into collation; the
902                // engine keeps those.
903                _ => None,
904            }
905        } else {
906            None
907        }
908    }
909
910    /// [`json_path`], loosened for existence: the projection may
911    /// be absent (a bare structural path) as well as the bare
912    /// `::`.
913    /// Whether a JSON path under a column reads the column as JSON
914    /// on the strength of its declaration alone: the column hop
915    /// (the first step) carries no `<json>` trait. Such a column is
916    /// an assumption of the plan ([`ColumnTypes::json`]); with the
917    /// trait the graft is declared on the hop and holds on both
918    /// roads.
919    fn note_json_column(&mut self, o: NodeId, col: &str) {
920        let declared_on_hop = self.kids(o, "step").first().is_some_and(|s| {
921            self.kids(*s, "trait").iter().any(|t| {
922                matches!(self.prop(*t, "alts"), Some(Value::List(alts))
923                    if alts.iter().any(|a| matches!(a, Value::Str(x) if x == "json")))
924            })
925        });
926        if !declared_on_hop && !self.column_types.json.iter().any(|c| c == col) {
927            self.column_types.json.push(col.to_string());
928        }
929    }
930
931    fn json_path_loose(&self, o: NodeId) -> Option<(String, Vec<String>)> {
932        if self.json_path(o).is_some() {
933            return self.json_path(o);
934        }
935        if self.kind(o) != "path" || self.kid(o, "projection").is_some() {
936            return None;
937        }
938        let steps = self.kids(o, "step");
939        if steps.len() < 2 {
940            return None;
941        }
942        let mut names = Vec::with_capacity(steps.len());
943        for s in &steps {
944            if self.prop_s(*s, "axis") != "/"
945                || self.prop_s(*s, "matcher-kind") != "name"
946                || self.kid(*s, "predicate").is_some()
947            {
948                return None;
949            }
950            let name = self.prop_s(*s, "matcher");
951            let plain = !name.is_empty()
952                && name
953                    .chars()
954                    .next()
955                    .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
956                && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
957            if !plain {
958                return None;
959            }
960            names.push(name);
961        }
962        let col = names.remove(0);
963        Some((col, names))
964    }
965
966    fn walk_all(&self, n: NodeId) -> Vec<NodeId> {
967        let mut out = vec![n];
968        let mut i = 0;
969        while i < out.len() {
970            out.extend(self.arbor.children(out[i]));
971            i += 1;
972        }
973        out
974    }
975
976    fn query(&mut self) -> Result<String, SqlError> {
977        let root = self.arbor.root();
978        let q = self
979            .kid(root, "query")
980            .ok_or_else(|| SqlError::Unsupported("empty query".into()))?;
981        let mut sel = Select::default();
982
983        // Correlations: exactly one becomes the JOIN's left table.
984        let corrs = self.kids(q, "query");
985        let branches = self.kids(q, "branch");
986        if branches.len() != 1 {
987            return Err(SqlError::Unsupported(
988                "a branch union (SQL has UNION, but result shapes differ; export one branch)"
989                    .into(),
990            ));
991        }
992
993        if corrs.len() > 1 {
994            return Err(SqlError::Unsupported(
995                "more than one correlation context".into(),
996            ));
997        }
998        if let Some(corr) = corrs.first() {
999            // Driver-first: the query's own branch is the FROM
1000            // table (the driver); the correlation entry is the
1001            // joined table, whose `$$` equalities form the ON.
1002            let (ltable, lpreds) = self.table_branch(branches[0])?;
1003            let (rtable, rpreds) = self.table_branch(self.kids(*corr, "branch")[0])?;
1004            // The SQL renderings of the two table names (validated
1005            // or quoted); the raw names stay in the plan metadata,
1006            // which the driver matches against its catalog.
1007            let lsql = self.sql_ident(&ltable, "table name")?;
1008            let rsql = self.sql_ident(&rtable, "table name")?;
1009            self.from_sql = lsql.clone();
1010            self.join_sql = Some(rsql.clone());
1011            // The driver's own predicates are plain WHERE.
1012            let driver_conds: Vec<NodeId> = lpreds;
1013            // Split the joined expression's predicates: `$$`
1014            // equalities form the ON, the rest the WHERE.
1015            let mut on = Vec::new();
1016            let mut wheres = Vec::new();
1017            for p in rpreds {
1018                self.split_join_pred(p, &rsql, &mut on, &mut wheres)?;
1019            }
1020            // `<=>?` — the outer correlation keeps a driver row no
1021            // joined row admits, its witness null: a LEFT JOIN. The
1022            // joined expression's own predicates then select the
1023            // witness, so they belong to the ON; in a WHERE they
1024            // would discard the unmatched rows again.
1025            let outer = matches!(self.prop(*corr, "outer"), Some(Value::Bool(true)));
1026            if outer {
1027                on.append(&mut wheres);
1028            }
1029            sel.join_outer = outer;
1030            if on.is_empty() {
1031                return Err(SqlError::Unsupported(
1032                    "a correlation without a '$$' equality (no JOIN condition)".into(),
1033                ));
1034            }
1035            for p in driver_conds {
1036                let cond = self.predicate_cond(p, Some(&lsql.clone()))?;
1037                wheres.push(cond);
1038            }
1039            // `<=>*` — every witness: the JOIN as SQL means it, one
1040            // row per matching pair; the plain `<=>` binds one.
1041            self.join_every = matches!(self.prop(*corr, "every"), Some(Value::Bool(true)));
1042            if !self.join_every {
1043                self.notes.push(
1044                    "JOIN: Quarb's binding is existential (one row per FROM row, \
1045                     bound to its first witness); SQL multiplies rows when \
1046                     several joined rows match"
1047                        .to_string(),
1048                );
1049            }
1050            sel.from = lsql.clone();
1051            self.from_table = ltable;
1052            self.join_table = Some(rtable);
1053            sel.join = Some((rsql.clone(), on.join(" AND ")));
1054            sel.wheres = wheres;
1055            // A terminal projection on the driving branch is a
1056            // one-column select of the FROM table.
1057            if let Some(proj) = self.kid(branches[0], "projection") {
1058                let col = self.projection_col(proj)?;
1059                let col = self.sql_ident(&col, "column name")?;
1060                sel.select.push(format!("{lsql}.{col}"));
1061            }
1062            if self
1063                .kid(self.kids(*corr, "branch")[0], "projection")
1064                .is_some()
1065            {
1066                return Err(SqlError::Unsupported(
1067                    "a projection on the joined expression (project the witness \
1068                     in the pipeline: '$$1::col')"
1069                        .into(),
1070                ));
1071            }
1072            self.pipeline(q, &mut sel, Some((&lsql, &rsql)))?;
1073        } else {
1074            let (table, preds) = self.table_branch(branches[0])?;
1075            sel.from = self.sql_ident(&table, "table name")?;
1076            self.from_table = table;
1077            for p in preds {
1078                let cond = self.predicate_cond(p, None)?;
1079                sel.wheres.push(cond);
1080            }
1081            // A terminal projection is a one-column select.
1082            if let Some(proj) = self.kid(branches[0], "projection") {
1083                let col = self.projection_col(proj)?;
1084                sel.select.push(self.sql_ident(&col, "column name")?);
1085            }
1086            self.pipeline(q, &mut sel, None)?;
1087        }
1088        Ok(sel.render())
1089    }
1090
1091    /// A `/table/*[preds]` branch: the table name and the row-step
1092    /// predicate nodes.
1093    fn table_branch(&mut self, b: NodeId) -> Result<(String, Vec<NodeId>), SqlError> {
1094        self.table_branch_lead(b, false)
1095    }
1096
1097    /// [`table_branch`]; with `more`, the branch may go on after
1098    /// `/table/*[…]` (a hop, a cell): the prefilter concerns its
1099    /// first two steps only, and the steps after them are held to
1100    /// the whole-query gates.
1101    fn table_branch_lead(
1102        &mut self,
1103        b: NodeId,
1104        more: bool,
1105    ) -> Result<(String, Vec<NodeId>), SqlError> {
1106        let steps = self.kids(b, "step");
1107        if steps.len() < 2 || (steps.len() > 2 && !more) {
1108            return Err(SqlError::Unsupported(
1109                "navigation beyond /table/* (SQL sees tables and rows)".into(),
1110            ));
1111        }
1112        let (t, rows) = (steps[0], steps[1]);
1113        if self.prop_s(t, "axis") != "/"
1114            || self.prop_s(t, "matcher-kind") != "name"
1115            || self.prop_s(rows, "axis") != "/"
1116            || self.prop_s(rows, "matcher-kind") != "any"
1117        {
1118            return Err(SqlError::Unsupported(
1119                "navigation beyond /table/* (SQL sees tables and rows)".into(),
1120            ));
1121        }
1122        if self.kid(t, "predicate").is_some() {
1123            return Err(SqlError::Unsupported("a predicate on the table hop".into()));
1124        }
1125        Ok((self.prop_s(t, "matcher"), self.kids(rows, "predicate")))
1126    }
1127
1128    /// One row predicate as a WHERE condition (qualify columns with
1129    /// `qualifier` when joining).
1130    fn predicate_cond(&mut self, p: NodeId, qual: Option<&str>) -> Result<String, SqlError> {
1131        if self.prop_s(p, "kind") != "expr" {
1132            return Err(SqlError::Unsupported(
1133                "a positional predicate on rows (SQL rows are unordered; ORDER BY + LIMIT)".into(),
1134            ));
1135        }
1136        let parts: Vec<String> = self
1137            .arbor
1138            .children(p)
1139            .into_iter()
1140            .map(|c| self.pred_expr(c, qual))
1141            .collect::<Result<_, _>>()?;
1142        Ok(parts.join(" AND "))
1143    }
1144
1145    fn pred_expr(&mut self, e: NodeId, qual: Option<&str>) -> Result<String, SqlError> {
1146        match self.kind(e).as_str() {
1147            "and" | "or" => {
1148                let op = self.kind(e).to_uppercase();
1149                let kids: Vec<String> = self
1150                    .arbor
1151                    .children(e)
1152                    .into_iter()
1153                    .map(|c| self.pred_expr(c, qual))
1154                    .collect::<Result<_, _>>()?;
1155                Ok(format!("({})", kids.join(&format!(" {op} "))))
1156            }
1157            "not" => {
1158                // SQL's `NOT` propagates UNKNOWN: `NOT (x = 5)` is
1159                // UNKNOWN for a NULL `x` and drops the row, but Quarb's
1160                // negation keeps it (the inner `value_eq` is false, so
1161                // its negation is true). Not provably identical without
1162                // the schema — the pushdown paths refuse it and scan.
1163                if self.strict {
1164                    return Err(SqlError::Semantics(
1165                        "SQL NOT propagates UNKNOWN, dropping the NULL rows \
1166                         Quarb keeps"
1167                            .into(),
1168                    ));
1169                }
1170                let inner: Vec<String> = self
1171                    .arbor
1172                    .children(e)
1173                    .into_iter()
1174                    .map(|c| self.pred_expr(c, qual))
1175                    .collect::<Result<_, _>>()?;
1176                Ok(format!("NOT ({})", inner.join(" AND ")))
1177            }
1178            "parens" => {
1179                let inner: Vec<String> = self
1180                    .arbor
1181                    .children(e)
1182                    .into_iter()
1183                    .map(|c| self.pred_expr(c, qual))
1184                    .collect::<Result<_, _>>()?;
1185                Ok(format!("({})", inner.join(" AND ")))
1186            }
1187            "compare" => {
1188                let op = self.prop_s(e, "op");
1189                let kids = self.arbor.children(e);
1190                // A comparison against a bare `null` literal. Quarb's
1191                // `value_eq` treats NULL as an ordinary value
1192                // (`value_eq(NULL, NULL)` is true, `value_eq(NULL, x)`
1193                // false), so `= null` keeps exactly the NULL rows and
1194                // `!= null` the non-NULL rows. SQL's `= NULL` / `<>
1195                // NULL` are always UNKNOWN and drop every row; the
1196                // `IS [NOT] NULL` forms are provably identical (and
1197                // portable across every target dialect).
1198                if matches!(op.as_str(), "=" | "!=")
1199                    && (self.is_null_literal(kids[0]) || self.is_null_literal(kids[1]))
1200                {
1201                    let other = if self.is_null_literal(kids[0]) {
1202                        kids[1]
1203                    } else {
1204                        kids[0]
1205                    };
1206                    let col = self.operand(other, qual)?;
1207                    return Ok(if op == "=" {
1208                        format!("{col} IS NULL")
1209                    } else {
1210                        format!("{col} IS NOT NULL")
1211                    });
1212                }
1213                // JSON-column-path pushdown: `[/col/a/b:: = 'lit']`
1214                // navigates into a JSON column and compares a fixed
1215                // path to a string literal. Only this exact shape —
1216                // fixed object path, string equality, and a literal
1217                // that does NOT look numeric — is provably identical
1218                // to the client-side graft (each engine's scalar
1219                // extractor unquotes to text, and an absent path or
1220                // non-string value excludes the row on both sides,
1221                // matching Quarb's `value_eq` on non-numeric text).
1222                // Numeric casts, `!=`, wildcards, and deeper
1223                // predicates fall through to the ordinary operand
1224                // logic below, which refuses the navigation; the
1225                // partial-pushdown prefilter ladder picks those up
1226                // with superset semantics. Enabled only when a
1227                // dialect is set.
1228                if op == "="
1229                    && let Some(dialect) = self.dialect
1230                {
1231                    for (pi, li) in [(0usize, 1usize), (1, 0)] {
1232                        if self.is_text_literal(kids[li])
1233                            && let Some((col, path)) = self.json_path(kids[pi])
1234                        {
1235                            self.note_json_column(kids[pi], &col);
1236                            // Quarb's value_eq compares numeric-looking
1237                            // strings numerically — '150' matches the
1238                            // JSON number 150, and the string "150.0".
1239                            // No engine's text extractor coerces that
1240                            // way, so the pushed compare would drop
1241                            // rows the graft keeps. Refuse; the
1242                            // prefilter ladder handles it as a
1243                            // superset.
1244                            let raw = self
1245                                .prop(kids[li], "value")
1246                                .map(|v| v.to_string())
1247                                .unwrap_or_default();
1248                            if raw.trim().parse::<f64>().is_ok() {
1249                                return Err(SqlError::Semantics(
1250                                    "a numeric-looking text literal against a \
1251                                     JSON path compares numerically in Quarb \
1252                                     (value coercion); no SQL extractor \
1253                                     matches that"
1254                                        .into(),
1255                                ));
1256                            }
1257                            let lit = self.operand(kids[li], qual)?;
1258                            let extract = json_extract(dialect, qual, &col, &path);
1259                            return Ok(json_valid_guard(
1260                                dialect,
1261                                qual,
1262                                &col,
1263                                format!("{extract} = {lit}"),
1264                            ));
1265                        }
1266                    }
1267                }
1268                // Any other JSON-path comparison: name the real
1269                // reason, not the generic flat-rows refusal — only
1270                // fixed-path string equality is provably identical
1271                // (Quarb coerces numeric-looking values; no
1272                // engine's extractor matches that). The partial
1273                // prefilter ladder covers these shapes.
1274                if self.dialect.is_some() {
1275                    for side in [kids[0], kids[1]] {
1276                        if self.json_path(side).is_some() || self.json_path_loose(side).is_some() {
1277                            return Err(SqlError::Semantics(
1278                                "a JSON-path comparison pushes whole only as \
1279                                 fixed-path string equality (Quarb coerces \
1280                                 numeric-looking values; no extractor matches \
1281                                 that); this shape rides the partial prefilter"
1282                                    .into(),
1283                            ));
1284                        }
1285                    }
1286                }
1287                // Quarb compares by value; SQL by the column's type.
1288                // A column against a numeric literal is the scan's
1289                // comparison only on a numeric-typed column, and
1290                // against a text literal only on a column that is
1291                // not (MySQL reads `n = 'abc'` as `n = 0`): the
1292                // catalog decides, so both are recorded for the
1293                // caller. A numeric-looking TEXT literal meets
1294                // numbers as a number in Quarb and compares as text
1295                // in SQL, on every engine, so it does not push.
1296                if self.strict {
1297                    for (ci, li) in [(0usize, 1usize), (1, 0)] {
1298                        let Some(column) = self.column_operand(kids[ci]) else {
1299                            continue;
1300                        };
1301                        if self.kind(kids[li]) != "literal" {
1302                            continue;
1303                        }
1304                        let numeric = self
1305                            .prop(kids[li], "value")
1306                            .is_some_and(|v| Value::Str(v.to_string()).numeric_reading().is_some());
1307                        let list = match (self.prop_s(kids[li], "type").as_str(), numeric) {
1308                            ("null", _) => continue,
1309                            ("text", true) => {
1310                                return Err(SqlError::Semantics(
1311                                    "a numeric-looking text literal compares \
1312                                     numerically in Quarb (value coercion); SQL \
1313                                     compares it as text"
1314                                        .into(),
1315                                ));
1316                            }
1317                            ("text", false) => &mut self.column_types.text,
1318                            (_, true) => &mut self.column_types.numeric,
1319                            (_, false) => continue,
1320                        };
1321                        if !list.contains(&column) {
1322                            list.push(column);
1323                        }
1324                    }
1325                }
1326                let l = self.operand(kids[0], qual)?;
1327                // Ruling #33: a pattern literal on `=` pushes as
1328                // LIKE — a `%` per star, each literal segment
1329                // escaped, in order. Anchoring matches exactly:
1330                // LIKE anchors both ends, a flanking star lifts
1331                // one. The case-folding caveat is `*=`'s; `!=`
1332                // with a pattern rides the scan (NOT LIKE drops
1333                // the NULL rows Quarb keeps).
1334                if self.kind(kids[1]) == "pattern" {
1335                    if op.as_str() != "=" {
1336                        return Err(SqlError::Unsupported(format!(
1337                            "a pattern literal on '{op}' (only '=' pushes)"
1338                        )));
1339                    }
1340                    // PostgreSQL's LIKE is case-sensitive under its
1341                    // deterministic collations — provably what the
1342                    // pattern test does — so the strict push is
1343                    // sound there (and a prefix pattern is
1344                    // index-sargable server-side). Everywhere else
1345                    // case folding is ambient state (SQLite pragma,
1346                    // MySQL/MSSQL collation), so strict refuses.
1347                    if self.strict && self.dialect != Some(Dialect::Postgres) {
1348                        return Err(SqlError::Semantics(
1349                            "LIKE case folding differs per engine \
1350                             (provably case-sensitive only on PostgreSQL)"
1351                                .into(),
1352                        ));
1353                    }
1354                    if !self.strict {
1355                        self.notes.push(
1356                            "pattern → LIKE: Quarb's pattern test is \
1357                             case-sensitive; LIKE folds case on \
1358                             SQLite/MySQL but not PostgreSQL"
1359                                .to_string(),
1360                        );
1361                    }
1362                    let mut like = String::new();
1363                    for kid in self.arbor.children(kids[1]) {
1364                        match self.kind(kid).as_str() {
1365                            "star" => like.push('%'),
1366                            _ => {
1367                                let raw = self
1368                                    .prop(kid, "value")
1369                                    .map(|v| v.to_string())
1370                                    .unwrap_or_default();
1371                                like.push_str(
1372                                    &raw.replace('\\', "\\\\")
1373                                        .replace('%', "\\%")
1374                                        .replace('_', "\\_")
1375                                        .replace('\'', "''"),
1376                                );
1377                            }
1378                        }
1379                    }
1380                    return Ok(format!("{l} LIKE '{like}' ESCAPE '\\'"));
1381                }
1382                let r = self.operand(kids[1], qual)?;
1383                Ok(match op.as_str() {
1384                    "=" => format!("{l} = {r}"),
1385                    "!=" => {
1386                        // Quarb keeps rows whose operand is NULL (its
1387                        // `value_eq` is false there, so `!=` is true);
1388                        // SQL's `<>` is UNKNOWN for a NULL operand and
1389                        // drops those rows. Not provably identical
1390                        // without the schema, so pushdown refuses it;
1391                        // the display translation keeps `<>` and notes
1392                        // the divergence.
1393                        if self.strict {
1394                            return Err(SqlError::Semantics(
1395                                "'!=' drops the NULL rows Quarb keeps \
1396                                 (SQL '<>' is UNKNOWN for NULL; use '!= null' \
1397                                 for IS NOT NULL)"
1398                                    .into(),
1399                            ));
1400                        }
1401                        self.notes.push(
1402                            "'!=' → '<>': Quarb keeps rows whose column is NULL; \
1403                             SQL's '<>' drops them (use '!= null' for IS NOT NULL)"
1404                                .to_string(),
1405                        );
1406                        format!("{l} <> {r}")
1407                    }
1408                    "<" | "<=" | ">" | ">=" => format!("{l} {op} {r}"),
1409                    "*=" => {
1410                        // The same PostgreSQL rung as the pattern
1411                        // literal above: LIKE is provably
1412                        // case-sensitive there, so `*=` pushes
1413                        // strict too.
1414                        if self.strict && self.dialect != Some(Dialect::Postgres) {
1415                            return Err(SqlError::Semantics(
1416                                "LIKE case folding differs per engine \
1417                                 (provably case-sensitive only on PostgreSQL)"
1418                                    .into(),
1419                            ));
1420                        }
1421                        // The pattern must be a text literal: a
1422                        // column or computed operand holds a value,
1423                        // not a pattern, and SQL LIKE cannot express
1424                        // "contains that value" portably.
1425                        if !self.is_text_literal(kids[1]) {
1426                            return Err(SqlError::Unsupported(
1427                                "'*=' with a non-literal pattern".into(),
1428                            ));
1429                        }
1430                        self.notes.push(
1431                            "*= → LIKE: Quarb's substring test is case-sensitive; LIKE \
1432                             folds case on SQLite/MySQL but not PostgreSQL"
1433                                .to_string(),
1434                        );
1435                        // Escape LIKE's metacharacters, then quote.
1436                        // The explicit ESCAPE makes '\' the escape
1437                        // everywhere — SQLite, MSSQL, and Oracle
1438                        // have no default escape character.
1439                        let raw = self
1440                            .prop(kids[1], "value")
1441                            .map(|v| v.to_string())
1442                            .unwrap_or_default();
1443                        let pat = raw
1444                            .replace('\\', "\\\\")
1445                            .replace('%', "\\%")
1446                            .replace('_', "\\_")
1447                            .replace('\'', "''");
1448                        format!("{l} LIKE '%{pat}%' ESCAPE '\\'")
1449                    }
1450                    "==" | "!==" | "=~" | "!~" => {
1451                        return Err(SqlError::Semantics(
1452                            "regex matching means a different REGEXP engine per \
1453                             backend; regexes run engine-side"
1454                                .into(),
1455                        ));
1456                    }
1457                    other => {
1458                        return Err(SqlError::Unsupported(format!("the '{other}' comparison")));
1459                    }
1460                })
1461            }
1462            // A bare truthy operand.
1463            _ => {
1464                if self.strict {
1465                    return Err(SqlError::Semantics(
1466                        "truthiness diverges (0 and '' are falsy in Quarb)".into(),
1467                    ));
1468                }
1469                self.notes.push(
1470                    "truthiness: '[::c]' exports as IS NOT NULL, but Quarb also treats \
1471                     0 and '' as falsy"
1472                        .to_string(),
1473                );
1474                Ok(format!("{} IS NOT NULL", self.operand(e, qual)?))
1475            }
1476        }
1477    }
1478
1479    fn operand(&mut self, o: NodeId, qual: Option<&str>) -> Result<String, SqlError> {
1480        match self.kind(o).as_str() {
1481            "literal" => {
1482                let v = self.prop(o, "value").unwrap_or(Value::Null);
1483                match self.prop_s(o, "type").as_str() {
1484                    "text" => {
1485                        let s = v.to_string();
1486                        // No single escaping is portable across the
1487                        // pushdown's target dialects: MySQL (default
1488                        // sql_mode) and BigQuery read `\` as an escape
1489                        // while SQLite/PostgreSQL/DuckDB take it
1490                        // literally, and BigQuery rejects the `''`
1491                        // quote-doubling the others require. A literal
1492                        // carrying either character cannot be pushed as
1493                        // provably identical SQL, so refuse it and let
1494                        // the caller scan. (The display translation
1495                        // keeps its best-effort `''`-doubling.)
1496                        if self.strict && (s.contains('\'') || s.contains('\\')) {
1497                            return Err(SqlError::Semantics(
1498                                "a text literal with a quote or backslash \
1499                                 has no escaping portable across SQL dialects"
1500                                    .into(),
1501                            ));
1502                        }
1503                        Ok(format!("'{}'", s.replace('\'', "''")))
1504                    }
1505                    "null" => Ok("NULL".to_string()),
1506                    _ => Ok(v.to_string()),
1507                }
1508            }
1509            "path" => {
1510                if self.kid(o, "step").is_some() {
1511                    // A step here is either navigation (refused) or
1512                    // a resolution chain (refused with the reason).
1513                    let s = self.kids(o, "step")[0];
1514                    if self.prop_s(s, "axis") == "-->" {
1515                        return Err(SqlError::Unsupported(
1516                            "a '-->' resolution chain: the foreign-key targets live in \
1517                             the schema, not the query — spell the join with '<=>' to \
1518                             export it"
1519                                .into(),
1520                        ));
1521                    }
1522                    return Err(SqlError::Unsupported(
1523                        "navigation inside a predicate (SQL rows are flat)".into(),
1524                    ));
1525                }
1526                let p = self
1527                    .kid(o, "projection")
1528                    .ok_or_else(|| SqlError::Unsupported("an empty path operand".into()))?;
1529                let col = self.projection_col(p)?;
1530                let col = self.sql_ident(&col, "column name")?;
1531                Ok(match qual {
1532                    Some(q) => format!("{q}.{col}"),
1533                    None => col,
1534                })
1535            }
1536            "context" => {
1537                // `$$1::col` — the joined expression's witness, in
1538                // pipeline position: the joined table's column.
1539                // Anything else is outside the verified-safe set.
1540                let p = self
1541                    .kid(o, "projection")
1542                    .ok_or_else(|| SqlError::Unsupported("a bare '$$N' reference".into()))?;
1543                let col = self.projection_col(p)?;
1544                let col = self.sql_ident(&col, "column name")?;
1545                if matches!(self.prop(o, "index"), Some(Value::Int(0))) {
1546                    // `$$0::col` — the driver, legal only inside the
1547                    // joined expression's ON bracket (the parser
1548                    // refuses it anywhere else).
1549                    if !self.in_on {
1550                        return Err(SqlError::Unsupported(
1551                            "a '$$0' reference outside the join's ON".into(),
1552                        ));
1553                    }
1554                    if self.kid(o, "step").is_some() {
1555                        return Err(SqlError::Unsupported(
1556                            "a '$$0' reference beyond a plain column ($$0::col)".into(),
1557                        ));
1558                    }
1559                    return Ok(format!("{}.{col}", self.from_sql.clone()));
1560                }
1561                if self.in_on {
1562                    return Err(SqlError::Unsupported(
1563                        "a '$$N' reference inside the ON (the driver is '$$0')".into(),
1564                    ));
1565                }
1566                let Some(join) = self.join_sql.clone() else {
1567                    return Err(SqlError::Unsupported(
1568                        "a '$$N' reference outside a correlation join".into(),
1569                    ));
1570                };
1571                match self.prop(o, "index") {
1572                    Some(Value::Int(1)) => Ok(format!("{join}.{col}")),
1573                    None => Err(SqlError::Unsupported("a bare '$$N' reference".into())),
1574                    Some(v) => Err(SqlError::Unsupported(format!(
1575                        "pushdown: $${v} beyond a two-branch correlation"
1576                    ))),
1577                }
1578            }
1579            "invoking" => {
1580                // `$$__::col` — the invoking position of an enclosing
1581                // query body, never the driver (that is `$$0`, a
1582                // context of index 0, since draft 153). SQL has no
1583                // enclosing body to read.
1584                Err(SqlError::Unsupported(
1585                    "a '$$__' reference (the driver inside the ON is '$$0')".into(),
1586                ))
1587            }
1588            "arith" => {
1589                let op = self.prop_s(o, "op");
1590                let kids = self.arbor.children(o);
1591                let l = self.operand(kids[0], qual)?;
1592                let r = self.operand(kids[1], qual)?;
1593                Ok(match op.as_str() {
1594                    "+" | "-" | "*" => format!("({l} {op} {r})"),
1595                    "div" => format!("({l} / {r})"),
1596                    "mod" => format!("({l} % {r})"),
1597                    other => return Err(SqlError::Unsupported(format!("'{other}' arithmetic"))),
1598                })
1599            }
1600            other => Err(SqlError::Unsupported(format!(
1601                "the '{other}' operand (registers, topics, and captures are Quarb-side state)"
1602            ))),
1603        }
1604    }
1605
1606    fn projection_col(&mut self, p: NodeId) -> Result<String, SqlError> {
1607        match self.prop_s(p, "kind").as_str() {
1608            "property" => match self.prop(p, "key") {
1609                Some(k) => Ok(k.to_string()),
1610                None => Err(SqlError::Unsupported(
1611                    "the bare '::' projection (name the column)".into(),
1612                )),
1613            },
1614            other => Err(SqlError::Unsupported(format!(
1615                "the {other} metadata projection"
1616            ))),
1617        }
1618    }
1619
1620    /// The column a plain column operand names (`::col`, `$*1::col`):
1621    /// a path without a step, or a context reference, projecting a
1622    /// named property.
1623    /// A numeric reducer (`sum`, `mean`, `min`, `max`) pushed over a
1624    /// column is the scan's only on a numeric-typed column: the
1625    /// scan lifts unit text (`'18 parasang'` under a declared unit)
1626    /// to quantities and orders texts as texts, where SQL sums a
1627    /// text column by its leading digits and orders it by
1628    /// collation. Recorded for the caller's catalog as a
1629    /// comparison's assumption is.
1630    fn assume_numeric(&mut self, column: Option<String>) {
1631        if !self.strict {
1632            return;
1633        }
1634        if let Some(c) = column
1635            && !self.column_types.numeric.contains(&c)
1636        {
1637            self.column_types.numeric.push(c);
1638        }
1639    }
1640
1641    fn column_operand(&self, o: NodeId) -> Option<String> {
1642        match self.kind(o).as_str() {
1643            "path" if self.kid(o, "step").is_none() => {}
1644            "context" => {}
1645            _ => return None,
1646        }
1647        let p = self.kid(o, "projection")?;
1648        if self.prop_s(p, "kind") != "property" {
1649            return None;
1650        }
1651        self.prop(p, "key").map(|k| k.to_string())
1652    }
1653
1654    /// Whether `o` is a text string literal (`'London'`).
1655    fn is_text_literal(&self, o: NodeId) -> bool {
1656        self.kind(o) == "literal" && self.prop_s(o, "type") == "text"
1657    }
1658
1659    /// If `o` is the one JSON-column-path shape pushdown handles —
1660    /// `/col/seg/seg…::`, a plain-navigation path (every hop `/`
1661    /// and a plain-identifier object key, no wildcards, no nested
1662    /// predicate), at least one segment past the column, ending in
1663    /// the bare `::` projection — return `(column, [json segments])`.
1664    /// Anything else is `None` (and falls back to the graft).
1665    fn json_path(&self, o: NodeId) -> Option<(String, Vec<String>)> {
1666        if self.kind(o) != "path" {
1667            return None;
1668        }
1669        let steps = self.kids(o, "step");
1670        if steps.len() < 2 {
1671            return None;
1672        }
1673        // The projection must be the bare `::` (default value of
1674        // the JSON leaf), not `::key` or a `:::`/`:` metadata form.
1675        let proj = self.kid(o, "projection")?;
1676        if self.prop_s(proj, "kind") != "property" || self.prop(proj, "key").is_some() {
1677            return None;
1678        }
1679        let mut names = Vec::with_capacity(steps.len());
1680        for s in &steps {
1681            if self.prop_s(*s, "axis") != "/"
1682                || self.prop_s(*s, "matcher-kind") != "name"
1683                || self.kid(*s, "predicate").is_some()
1684            {
1685                return None;
1686            }
1687            let name = self.prop_s(*s, "matcher");
1688            // Plain object keys only — no array indices, no
1689            // characters that would need per-dialect path escaping.
1690            let plain = !name.is_empty()
1691                && name
1692                    .chars()
1693                    .next()
1694                    .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
1695                && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
1696            if !plain {
1697                return None;
1698            }
1699            names.push(name);
1700        }
1701        let col = names.remove(0);
1702        Some((col, names))
1703    }
1704
1705    /// A safe `AS` alias: bare when it is a plain identifier and
1706    /// not an SQL keyword; otherwise strict mode refuses (quoting
1707    /// dialects disagree) and export mode double-quotes, noting it.
1708    fn alias(&mut self, name: &str) -> Result<String, SqlError> {
1709        if is_plain_ident(name) {
1710            return Ok(name.to_string());
1711        }
1712        if self.strict {
1713            return Err(SqlError::Unsupported(format!(
1714                "pushdown: field name {name:?} needs SQL quoting \
1715                 (dialects disagree); rename the field"
1716            )));
1717        }
1718        self.notes
1719            .push(format!("field name {name:?} double-quoted (ANSI)"));
1720        Ok(format!("\"{}\"", name.replace('"', "\"\"")))
1721    }
1722
1723    /// A table or column name rendered into SQL. Bare when it is a
1724    /// plain identifier; otherwise strict mode refuses — a name
1725    /// like `a OR b` would silently rewrite the emitted SQL's
1726    /// meaning, breaking the provably-identical guarantee (and a
1727    /// portable quoting does not exist) — and export mode
1728    /// double-quotes with a note.
1729    fn sql_ident(&mut self, name: &str, what: &str) -> Result<String, SqlError> {
1730        if is_plain_ident(name) {
1731            return Ok(name.to_string());
1732        }
1733        if self.strict {
1734            return Err(SqlError::Unsupported(format!(
1735                "pushdown: {what} {name:?} is not a plain SQL identifier"
1736            )));
1737        }
1738        self.notes
1739            .push(format!("{what} {name:?} double-quoted (ANSI)"));
1740        Ok(format!("\"{}\"", name.replace('"', "\"\"")))
1741    }
1742
1743    /// Split a joined-side predicate: `col = $*1::col2` equalities
1744    /// become the ON condition; everything else the WHERE.
1745    /// `ltable` and `rtable` are the tables' SQL renderings.
1746    fn split_join_pred(
1747        &mut self,
1748        p: NodeId,
1749        rtable: &str,
1750        on: &mut Vec<String>,
1751        wheres: &mut Vec<String>,
1752    ) -> Result<(), SqlError> {
1753        if self.prop_s(p, "kind") != "expr" {
1754            return Err(SqlError::Unsupported(
1755                "a positional predicate on the joined side".into(),
1756            ));
1757        }
1758        // Flatten top-level ANDs; each conjunct routes to ON or
1759        // WHERE.
1760        fn conjuncts(ex: &Exporter, e: NodeId, out: &mut Vec<NodeId>) {
1761            if ex.kind(e) == "and" {
1762                for c in ex.arbor.children(e) {
1763                    conjuncts(ex, c, out);
1764                }
1765            } else {
1766                out.push(e);
1767            }
1768        }
1769        let mut parts = Vec::new();
1770        for c in self.arbor.children(p) {
1771            conjuncts(self, c, &mut parts);
1772        }
1773        for e in parts {
1774            let uses_driver = self.subtree_has_driver(e);
1775            self.in_on = true;
1776            let cond = self.pred_expr(e, Some(rtable));
1777            self.in_on = false;
1778            let cond = cond?;
1779            if uses_driver && self.kind(e) == "compare" && self.prop_s(e, "op") == "=" {
1780                // Record which joined-table columns the ON binds —
1781                // the uniqueness obligation (see
1782                // Pushdown::join_left). Collected from the arbor's
1783                // bare-column operand nodes, never from the
1784                // rendered SQL text, so neither a literal nor an
1785                // unusual column name can corrupt the obligation.
1786                self.collect_join_cols(e)?;
1787                on.push(cond);
1788            } else {
1789                wheres.push(cond);
1790            }
1791        }
1792        Ok(())
1793    }
1794
1795    /// The joined-table columns the ON equality binds: every bare
1796    /// column operand (`::col`) in `e`'s subtree, appended to the
1797    /// join obligation with their raw (catalog) names.
1798    fn collect_join_cols(&mut self, e: NodeId) -> Result<(), SqlError> {
1799        // The `$$0` side is the driver — not part of the joined
1800        // table's obligation.
1801        if self.is_driver(e) {
1802            return Ok(());
1803        }
1804        if self.kind(e) == "path"
1805            && self.kid(e, "step").is_none()
1806            && let Some(p) = self.kid(e, "projection")
1807        {
1808            let col = self.projection_col(p)?;
1809            self.join_on_cols.push(col);
1810        }
1811        for c in self.arbor.children(e) {
1812            self.collect_join_cols(c)?;
1813        }
1814        Ok(())
1815    }
1816
1817    /// `$$0`: a context operand of index 0 (the driver).
1818    fn is_driver(&self, n: NodeId) -> bool {
1819        self.kind(n) == "context" && matches!(self.prop(n, "index"), Some(Value::Int(0)))
1820    }
1821
1822    fn subtree_has_driver(&self, n: NodeId) -> bool {
1823        self.is_driver(n)
1824            || self
1825                .arbor
1826                .children(n)
1827                .into_iter()
1828                .any(|c| self.subtree_has_driver(c))
1829    }
1830
1831    /// Consume the pipeline into SELECT clauses.
1832    fn pipeline(
1833        &mut self,
1834        q: NodeId,
1835        sel: &mut Select,
1836        join: Option<(&str, &str)>,
1837    ) -> Result<(), SqlError> {
1838        let Some(pipe) = self.kid(q, "pipeline") else {
1839            return Ok(());
1840        };
1841        let commands: Vec<NodeId> = self.arbor.children(pipe);
1842        let mut i = 0;
1843        // A pending per-row value (`| ::col`) feeding an aggregate,
1844        // and the column it names where it is one.
1845        let mut pending_col: Option<String> = None;
1846        let mut pending_name: Option<String> = None;
1847        // After a grouped reduction: (key, agg_sql, alias).
1848        let mut grouped: Option<(String, String, String)> = None;
1849        // A pushed key awaiting its fold: (the regula's name, key_sql).
1850        let mut pushed_key: Option<(String, String)> = None;
1851
1852        while i < commands.len() {
1853            let s = commands[i];
1854            match self.kind(s).as_str() {
1855                "expr" => {
1856                    let kids = self.arbor.children(s);
1857                    pending_col = Some(self.operand(kids[0], join.map(|(l, _)| l))?);
1858                    pending_name = self.column_operand(kids[0]);
1859                }
1860                "cmd" => {
1861                    let name = self.prop_s(s, "name");
1862                    match name.as_str() {
1863                        "rec" | "record" => {
1864                            sel.select = self.record_fields(s, join)?;
1865                        }
1866                        // A reducing aggregate on the plain pipe:
1867                        // the grouped reduction.
1868                        "count" | "sum" | "mean" | "avg" | "min" | "max" => {
1869                            let (key, _, _) = grouped.as_ref().ok_or_else(|| {
1870                                SqlError::Unsupported(format!(
1871                                    "'| {name}' outside a group (use '@| {name}')"
1872                                ))
1873                            })?;
1874                            // Quarb's count counts every member,
1875                            // nulls included: COUNT(*), never the
1876                            // NULL-skipping COUNT(col).
1877                            let col = if name == "count" {
1878                                pending_col = None;
1879                                None
1880                            } else {
1881                                self.assume_numeric(pending_name.take());
1882                                pending_col.take()
1883                            };
1884                            let agg = sql_agg(&name, col)?;
1885                            grouped = Some((key.clone(), agg.clone(), agg));
1886                        }
1887                        other => {
1888                            // sort/unique/top and kin are spellable
1889                            // in SQL but with the backend's own
1890                            // collation and duplicate semantics —
1891                            // name the divergence, not a missing
1892                            // feature.
1893                            if matches!(other, "sort" | "sort_by" | "unique" | "top" | "bottom") {
1894                                return Err(SqlError::Semantics(format!(
1895                                    "'{other}' means the backend's collation and \
1896                                     duplicate semantics; one engine-side ordering \
1897                                     keeps it identical everywhere"
1898                                )));
1899                            }
1900                            return Err(SqlError::Unsupported(format!(
1901                                "the '{other}' pipeline command"
1902                            )));
1903                        }
1904                    }
1905                }
1906                "push" => {
1907                    // An alias for the grouped aggregate.
1908                    if let Some((k, agg, _)) = grouped.take() {
1909                        let alias = self.prop_s(s, "name");
1910                        grouped = Some((k, agg, alias));
1911                    } else {
1912                        return Err(SqlError::Unsupported(
1913                            "a register push (Quarb-side state)".into(),
1914                        ));
1915                    }
1916                }
1917                // `| .k(::k)` before a fold by `.k`: the GROUP BY key
1918                // (a projection body is a subcontext of one branch).
1919                "expr-push" if grouped.is_none() && pushed_key.is_none() => {
1920                    let kids = self.arbor.children(s);
1921                    let key = self.operand(kids[0], join.map(|(l, _)| l))?;
1922                    pushed_key = Some((self.prop_s(s, "name"), key));
1923                }
1924                "subcontext" if grouped.is_none() && pushed_key.is_none() => {
1925                    let key = self.pushed_column(s, join.map(|(l, _)| l))?;
1926                    pushed_key = Some((self.prop_s(s, "name"), key));
1927                }
1928                "filter" => {
1929                    if grouped.is_some() {
1930                        // HAVING: `$_` / the alias refer to the
1931                        // aggregate.
1932                        let cond = self.having_cond(s)?;
1933                        sel.having = Some(cond);
1934                    } else {
1935                        return Err(SqlError::Unsupported(
1936                            "a mid-pipeline filter (put it in the row predicate)".into(),
1937                        ));
1938                    }
1939                }
1940                "recall" => {
1941                    // `| %.` finalizes the grouped record.
1942                    if self.prop_s(s, "ref") != "%." {
1943                        return Err(SqlError::Unsupported(
1944                            "a register recall (Quarb-side state)".into(),
1945                        ));
1946                    }
1947                    let (key, agg, alias) = grouped.clone().ok_or_else(|| {
1948                        SqlError::Unsupported("'%.', with nothing grouped".into())
1949                    })?;
1950                    let alias = self.alias(&alias)?;
1951                    sel.select = vec![key.clone(), format!("{agg} AS {alias}")];
1952                    // The HAVING condition compared the aggregate
1953                    // through $_ — substitute the real expression.
1954                    if let Some(h) = sel.having.take() {
1955                        sel.having = Some(h.replace("__AGG__", &agg));
1956                    }
1957                }
1958                "agg" if self.prop(s, "group").is_some() => {
1959                    // `@|{.k} agg`: the fold by the pushed key is the
1960                    // grouped reduction, GROUP BY key.
1961                    let name = self.prop_s(s, "name");
1962                    if !matches!(
1963                        name.as_str(),
1964                        "count" | "sum" | "mean" | "avg" | "min" | "max"
1965                    ) {
1966                        return Err(SqlError::Unsupported(format!(
1967                            "the '{name}' command per group (GROUP BY reduces)"
1968                        )));
1969                    }
1970                    let selector = self.prop_s(s, "group");
1971                    if selector.contains(';') {
1972                        return Err(SqlError::Unsupported(
1973                            "a fold by several regulae (one GROUP BY key translates)".into(),
1974                        ));
1975                    }
1976                    let (reg, key) = pushed_key.take().ok_or_else(|| {
1977                        SqlError::Unsupported("a fold by a regula no push of a key made".into())
1978                    })?;
1979                    if selector != "." && selector != format!(".{reg}") {
1980                        return Err(SqlError::Unsupported(format!(
1981                            "a fold by '{selector}' (the pushed key is '.{reg}')"
1982                        )));
1983                    }
1984                    if self.strict {
1985                        return Err(SqlError::Semantics(
1986                            "GROUP BY result order is unordered in SQL".into(),
1987                        ));
1988                    }
1989                    sel.group_by = Some(key.clone());
1990                    let col = if name == "count" {
1991                        pending_col = None;
1992                        None
1993                    } else {
1994                        self.assume_numeric(pending_name.take());
1995                        pending_col.take()
1996                    };
1997                    let agg = sql_agg(&name, col)?;
1998                    grouped = Some((key, agg.clone(), agg));
1999                }
2000                "agg" => {
2001                    let name = self.prop_s(s, "name");
2002                    match name.as_str() {
2003                        "count" | "sum" | "mean" | "avg" | "min" | "max" => {
2004                            // Quarb's count counts every row, nulls
2005                            // included: COUNT(*) regardless of a
2006                            // pending column.
2007                            let col = if name == "count" {
2008                                pending_col = None;
2009                                None
2010                            } else {
2011                                self.assume_numeric(pending_name.take());
2012                                pending_col.take()
2013                            };
2014                            sel.select = vec![sql_agg(&name, col)?];
2015                            self.aggregate = true;
2016                        }
2017                        "sort_by" => {
2018                            if self.strict {
2019                                return Err(SqlError::Semantics(
2020                                    "ORDER BY collations differ per engine".into(),
2021                                ));
2022                            }
2023                            // A sort after a positional selection
2024                            // (or a second sort) cannot render: the
2025                            // fixed SELECT shape orders before
2026                            // LIMIT, and has one ORDER BY.
2027                            if sel.limit.is_some() {
2028                                return Err(SqlError::Unsupported(
2029                                    "a sort after a positional selection (SQL orders \
2030                                     before LIMIT)"
2031                                        .into(),
2032                                ));
2033                            }
2034                            if sel.order_by.is_some() {
2035                                return Err(SqlError::Unsupported(
2036                                    "a second sort (SQL has a single ORDER BY)".into(),
2037                                ));
2038                            }
2039                            let kids = self.arbor.children(s);
2040                            // The options are the command's own:
2041                            // `--desc` is the direction, a named
2042                            // collation (`--locale=tag`, ruling
2043                            // 2026-11-11) is the engine's order and no
2044                            // backend's; a second key has no place in
2045                            // the one ORDER BY this shape holds.
2046                            let mut desc = false;
2047                            for &k in &kids[1..] {
2048                                if self.kind(k) != "option" {
2049                                    return Err(SqlError::Unsupported(
2050                                        "a sort by several keys".into(),
2051                                    ));
2052                                }
2053                                match self.prop_s(k, "name").as_str() {
2054                                    "--desc" | "-d" => desc = true,
2055                                    "--locale" => {
2056                                        return Err(SqlError::Semantics(
2057                                            "sort_by(--locale=…) names the engine's collation; \
2058                                             a backend's differs"
2059                                                .into(),
2060                                        ));
2061                                    }
2062                                    other => {
2063                                        return Err(SqlError::Unsupported(format!(
2064                                            "the '{other}' option of sort_by"
2065                                        )));
2066                                    }
2067                                }
2068                            }
2069                            let e = self.operand(kids[0], join.map(|(l, _)| l))?;
2070                            sel.order_by = Some((e, desc));
2071                        }
2072                        "reverse" => match &mut sel.order_by {
2073                            Some((_, desc)) => *desc = true,
2074                            None => {
2075                                return Err(SqlError::Unsupported(
2076                                    "reverse without an ORDER BY (rows are unordered)".into(),
2077                                ));
2078                            }
2079                        },
2080                        "top" => {
2081                            if self.strict {
2082                                return Err(SqlError::Semantics(
2083                                    "ORDER BY collations differ per engine".into(),
2084                                ));
2085                            }
2086                            if sel.limit.is_some() {
2087                                return Err(SqlError::Unsupported(
2088                                    "'top' after a positional selection (SQL orders \
2089                                     before LIMIT)"
2090                                        .into(),
2091                                ));
2092                            }
2093                            if sel.order_by.is_some() {
2094                                return Err(SqlError::Unsupported(
2095                                    "a second sort (SQL has a single ORDER BY)".into(),
2096                                ));
2097                            }
2098                            let kids = self.arbor.children(s);
2099                            let n = self.prop_s(kids[0], "value");
2100                            let e = self.operand(kids[1], join.map(|(l, _)| l))?;
2101                            sel.order_by = Some((e, true));
2102                            sel.limit = Some(n);
2103                        }
2104                        "unique" => {
2105                            if self.strict {
2106                                return Err(SqlError::Unsupported(
2107                                    "pushdown: DISTINCT result order is unordered in SQL".into(),
2108                                ));
2109                            }
2110                            // Quarb dedups the limited rows; SQL
2111                            // applies DISTINCT before LIMIT.
2112                            if sel.limit.is_some() {
2113                                return Err(SqlError::Unsupported(
2114                                    "'unique' after a positional selection (SQL applies \
2115                                     DISTINCT before LIMIT)"
2116                                        .into(),
2117                                ));
2118                            }
2119                            if let Some(c) = pending_col.take() {
2120                                sel.select = vec![c];
2121                            }
2122                            sel.distinct = true;
2123                        }
2124                        other => {
2125                            return Err(SqlError::Unsupported(format!("the '{other}' aggregate")));
2126                        }
2127                    }
2128                }
2129                "select" => {
2130                    if self.strict {
2131                        return Err(SqlError::Unsupported(
2132                            "pushdown: LIMIT without a guaranteed order".into(),
2133                        ));
2134                    }
2135                    // `@| [..n]` → LIMIT.
2136                    if sel.limit.is_some() {
2137                        return Err(SqlError::Unsupported(
2138                            "a second positional selection".into(),
2139                        ));
2140                    }
2141                    let p = self.arbor.children(s)[0];
2142                    match (self.prop_s(p, "kind").as_str(), self.prop(p, "to")) {
2143                        ("range", Some(Value::Int(n)))
2144                            if self.prop(p, "from").is_none() && n > 0 =>
2145                        {
2146                            sel.limit = Some(n.to_string());
2147                        }
2148                        _ => {
2149                            return Err(SqlError::Unsupported(
2150                                "positional selection beyond '@| [..n]'".into(),
2151                            ));
2152                        }
2153                    }
2154                }
2155                other => {
2156                    return Err(SqlError::Unsupported(format!(
2157                        "the '{other}' command (windows, subcontexts, and registers are \
2158                         Quarb-side state)"
2159                    )));
2160                }
2161            }
2162            i += 1;
2163        }
2164        // A pending column with no aggregate is a one-column select.
2165        if let Some(c) = pending_col
2166            && sel.select.is_empty()
2167        {
2168            sel.select = vec![c];
2169        }
2170        // A grouped reduction never recorded (`@|{.k} count` with no
2171        // `| .n | %.`) answers one value per group: the aggregate
2172        // alone, grouped by the key.
2173        if let Some((_, agg, _)) = grouped
2174            && sel.select.is_empty()
2175        {
2176            sel.select = vec![agg];
2177        }
2178        Ok(())
2179    }
2180
2181    /// The column a pushed projection body names — `.k(::k)` is a
2182    /// subcontext whose one branch is the bare projection; any
2183    /// other body is Quarb-side state.
2184    fn pushed_column(&mut self, s: NodeId, qual: Option<&str>) -> Result<String, SqlError> {
2185        let body = || {
2186            let q = self.kid(s, "query")?;
2187            let b = self.kid(q, "branch")?;
2188            let p = self.kid(b, "projection")?;
2189            let bare = self.kids(q, "branch").len() == 1
2190                && self.kids(q, "pipeline").is_empty()
2191                && self.arbor.children(b).len() == 1
2192                && self.prop_s(p, "kind") == "property";
2193            bare.then_some(p)
2194        };
2195        let p = body()
2196            .ok_or_else(|| SqlError::Unsupported("a pushed body (Quarb-side state)".into()))?;
2197        let col = self.projection_col(p)?;
2198        let col = self.sql_ident(&col, "column name")?;
2199        Ok(match qual {
2200            Some(q) => format!("{q}.{col}"),
2201            None => col,
2202        })
2203    }
2204
2205    /// A HAVING filter: `$_` and `$.name` refer to the aggregate.
2206    fn having_cond(&mut self, s: NodeId) -> Result<String, SqlError> {
2207        let kids = self.arbor.children(s);
2208        if kids.len() != 1 || self.kind(kids[0]) != "compare" {
2209            return Err(SqlError::Unsupported(
2210                "HAVING translates for a single comparison".into(),
2211            ));
2212        }
2213        let e = kids[0];
2214        let op = self.prop_s(e, "op");
2215        let cmp_kids = self.arbor.children(e);
2216        let l = match self.kind(cmp_kids[0]).as_str() {
2217            "topic" | "recall" => "__AGG__".to_string(),
2218            _ => {
2219                return Err(SqlError::Unsupported(
2220                    "HAVING compares the aggregate ($_ or its register)".into(),
2221                ));
2222            }
2223        };
2224        let r = self.operand(cmp_kids[1], None)?;
2225        Ok(format!("{l} {op} {r}"))
2226    }
2227
2228    /// `rec(...)` fields as a select list.
2229    fn record_fields(
2230        &mut self,
2231        s: NodeId,
2232        join: Option<(&str, &str)>,
2233    ) -> Result<Vec<String>, SqlError> {
2234        let kids = self.arbor.children(s);
2235        let mut fields = Vec::new();
2236        let mut i = 0;
2237        while i < kids.len() {
2238            let k = kids[i];
2239            if self.kind(k) == "literal" {
2240                let name = self.prop_s(k, "value");
2241                let value = self.operand(kids[i + 1], join.map(|(l, _)| l))?;
2242                let name = self.alias(&name)?;
2243                fields.push(format!("{value} AS {name}"));
2244                i += 2;
2245            } else {
2246                let value = self.operand(k, join.map(|(l, _)| l))?;
2247                fields.push(value);
2248                i += 1;
2249            }
2250        }
2251        Ok(fields)
2252    }
2253}
2254
2255fn sql_agg(name: &str, col: Option<String>) -> Result<String, SqlError> {
2256    let f = match name {
2257        "count" => "COUNT",
2258        "sum" => "SUM",
2259        "mean" | "avg" => "AVG",
2260        "min" => "MIN",
2261        "max" => "MAX",
2262        _ => unreachable!("checked by caller"),
2263    };
2264    match col {
2265        Some(c) => Ok(format!("{f}({c})")),
2266        // Only COUNT aggregates bare rows; SUM(*) and friends are
2267        // not SQL.
2268        None if f == "COUNT" => Ok("COUNT(*)".to_string()),
2269        None => Err(SqlError::Unsupported(format!(
2270            "'{name}' over row nodes (project a column first: '| ::col @| {name}')"
2271        ))),
2272    }
2273}
2274
2275#[cfg(test)]
2276mod null_and_literal_tests {
2277    use super::{Dialect, export, partial_pushdown, pushdown};
2278
2279    // Grouped pipeline that never pushes, so `partial_pushdown` hinges
2280    // only on the leading predicate (mirrors the crate's partial gate).
2281    const GROUPED: &str = " | ::x | .g(::x) @|{.g} count | .n | %.";
2282
2283    #[test]
2284    fn pattern_literal_pushes_as_like() {
2285        // Ruling #33: segments in order, a `%` per star, LIKE's
2286        // metacharacters escaped. Strict push only where LIKE is
2287        // provably case-sensitive (PostgreSQL); everywhere else the
2288        // pattern rides the scan.
2289        let q = "/users/*[::name == 'app-'*]::id";
2290        let p = pushdown(q, Some(Dialect::Postgres)).unwrap();
2291        assert_eq!(
2292            p.sql,
2293            "SELECT id FROM users WHERE name LIKE 'app-%' ESCAPE '\\'"
2294        );
2295        assert!(pushdown(q, Some(Dialect::Sqlite)).is_none());
2296        assert!(pushdown(q, Some(Dialect::MySql)).is_none());
2297        // contains and multi-segment shapes
2298        let p = pushdown("/users/*[::name == *'web'*]::id", Some(Dialect::Postgres)).unwrap();
2299        assert!(p.sql.contains("LIKE '%web%'"), "{}", p.sql);
2300        let p = pushdown(
2301            "/users/*[::name == *'a'*'.gz']::id",
2302            Some(Dialect::Postgres),
2303        )
2304        .unwrap();
2305        assert!(p.sql.contains("LIKE '%a%.gz'"), "{}", p.sql);
2306        // LIKE metacharacters in a segment are escaped
2307        let p = pushdown("/users/*[::name == *'50%_x'*]::id", Some(Dialect::Postgres)).unwrap();
2308        assert!(p.sql.contains("LIKE '%50\\%\\_x%'"), "{}", p.sql);
2309        // `!=` with a pattern rides the scan
2310        assert!(pushdown("/users/*[::name !== *'web'*]::id", Some(Dialect::Postgres)).is_none());
2311        // the `*=` alias gains the same PostgreSQL rung
2312        let p = pushdown("/users/*[::name *= 'web']::id", Some(Dialect::Postgres)).unwrap();
2313        assert!(p.sql.contains("LIKE '%web%'"), "{}", p.sql);
2314        assert!(pushdown("/users/*[::name *= 'web']::id", Some(Dialect::Sqlite)).is_none());
2315    }
2316
2317    #[test]
2318    fn json_column_path_pushdown_per_dialect() {
2319        // `[/col/a/b:: = 'lit']` navigates into a JSON column; each
2320        // dialect extracts the fixed path to text and compares.
2321        // Verified live against all five engines to match the graft.
2322        let q = "/orders/*[/data/meta/tier:: = 'gold']::id";
2323        let sql = |d| pushdown(q, Some(d)).unwrap().sql;
2324        assert_eq!(
2325            sql(Dialect::Postgres),
2326            "SELECT id FROM orders WHERE ((data::jsonb #>> '{meta,tier}') = 'gold')"
2327        );
2328        assert_eq!(
2329            sql(Dialect::MySql),
2330            "SELECT id FROM orders WHERE (JSON_VALID(data) AND \
2331             JSON_UNQUOTE(JSON_EXTRACT(data, '$.meta.tier')) = 'gold')"
2332        );
2333        assert_eq!(
2334            sql(Dialect::Sqlite),
2335            "SELECT id FROM orders WHERE (json_valid(data) AND \
2336             json_extract(data, '$.meta.tier') = 'gold')"
2337        );
2338        assert_eq!(
2339            sql(Dialect::Mssql),
2340            "SELECT id FROM orders WHERE (ISJSON(data) = 1 AND \
2341             JSON_VALUE(data, '$.meta.tier') = 'gold')"
2342        );
2343        assert_eq!(
2344            sql(Dialect::Oracle),
2345            "SELECT id FROM orders WHERE (JSON_VALUE(data, '$.meta.tier') = 'gold')"
2346        );
2347        // With no dialect, the JSON navigation is not pushable — it
2348        // falls back to the client-side graft.
2349        assert!(pushdown(q, None).is_none());
2350    }
2351
2352    #[test]
2353    fn json_pushdown_only_string_equality() {
2354        // Numeric comparison, `!=`, and a wildcard hop stay off the
2355        // pushdown path (they are not provably identical to the
2356        // graft), so they refuse and scan even with a dialect set.
2357        let d = Some(Dialect::Sqlite);
2358        assert!(pushdown("/o/*[/data/n:: > 2]::id", d).is_none());
2359        assert!(pushdown("/o/*[/data/tier:: != 'gold']::id", d).is_none());
2360        assert!(pushdown("/o/*[/data/items/*/sku:: = 'A1']::id", d).is_none());
2361    }
2362
2363    #[test]
2364    fn json_pushdown_refuses_numeric_looking_literal() {
2365        // value_eq coerces numeric-looking strings ('150' matches
2366        // the JSON number 150 and the string "150.0"); no engine's
2367        // extractor does, so the push would drop rows.
2368        let q = "/orders/*[/data/total:: = '150']::id";
2369        assert!(pushdown(q, Some(Dialect::Sqlite)).is_none());
2370        assert!(pushdown(q, Some(Dialect::Postgres)).is_none());
2371    }
2372
2373    #[test]
2374    fn partial_json_prefilters_sqlite() {
2375        // Exact string equality rides the strict gate.
2376        let p = partial_pushdown(
2377            "/orders/*[/payload/customer/geo/city:: = 'Lyon']::id",
2378            Some(Dialect::Sqlite),
2379        )
2380        .unwrap();
2381        assert_eq!(p.table, "orders");
2382        assert_eq!(
2383            p.where_sql,
2384            "(json_valid(payload) AND \
2385             json_extract(payload, '$.customer.geo.city') = 'Lyon')"
2386        );
2387        // Numeric comparison: typed compare, text values escape.
2388        let p = partial_pushdown(
2389            "/orders/*[/payload/total:: > 150]::id",
2390            Some(Dialect::Sqlite),
2391        )
2392        .unwrap();
2393        assert_eq!(
2394            p.where_sql,
2395            "(json_valid(payload) AND (json_extract(payload, '$.total') > 150 \
2396             OR json_type(payload, '$.total') = 'text'))"
2397        );
2398        // Bare existence.
2399        let p = partial_pushdown("/orders/*[/payload/gift]::id", Some(Dialect::Sqlite)).unwrap();
2400        assert_eq!(
2401            p.where_sql,
2402            "(json_valid(payload) AND json_type(payload, '$.gift') IS NOT NULL)"
2403        );
2404        // != floors at existence.
2405        let p = partial_pushdown(
2406            "/orders/*[/payload/status:: != 'x']::id",
2407            Some(Dialect::Sqlite),
2408        )
2409        .unwrap();
2410        assert_eq!(
2411            p.where_sql,
2412            "(json_valid(payload) AND json_type(payload, '$.status') IS NOT NULL)"
2413        );
2414        // A flipped literal flips the operator.
2415        let p = partial_pushdown(
2416            "/orders/*[150 < /payload/total::]::id",
2417            Some(Dialect::Sqlite),
2418        )
2419        .unwrap();
2420        assert!(p.where_sql.contains("> 150"), "{}", p.where_sql);
2421        // Without a dialect, JSON predicates stay on the engine.
2422        assert!(partial_pushdown("/orders/*[/payload/gift]::id", None).is_none());
2423    }
2424
2425    #[test]
2426    fn partial_json_prefilters_postgres() {
2427        let p = partial_pushdown(
2428            "/orders/*[/payload/total:: > 150]::id",
2429            Some(Dialect::Postgres),
2430        )
2431        .unwrap();
2432        assert_eq!(
2433            p.where_sql,
2434            "(CASE WHEN jsonb_typeof(payload::jsonb #> '{total}') = 'number' \
2435             THEN ((payload::jsonb #>> '{total}'))::float8 > 150 \
2436             WHEN jsonb_typeof(payload::jsonb #> '{total}') = 'string' \
2437             THEN true ELSE false END)"
2438        );
2439        let p = partial_pushdown("/orders/*[/payload/gift]::id", Some(Dialect::Postgres)).unwrap();
2440        assert_eq!(
2441            p.where_sql,
2442            "(jsonb_typeof(payload::jsonb #> '{gift}') IS NOT NULL)"
2443        );
2444    }
2445
2446    #[test]
2447    fn partial_skips_untranslatable_keeps_prefix() {
2448        // A refused predicate no prefilter covers is skipped — the
2449        // shorter conjunction is still a superset (the engine
2450        // re-applies the original) — rather than aborting the plan.
2451        let p = partial_pushdown(
2452            "/orders/*[::status = 'shipped'][/payload/line_items/*/sku:: = 'X']::id",
2453            Some(Dialect::Sqlite),
2454        )
2455        .unwrap();
2456        assert_eq!(p.where_sql, "status = 'shipped'");
2457    }
2458
2459    #[test]
2460    fn null_literal_compares_use_is_null() {
2461        // `= null` / `!= null` are provably identical to Quarb's
2462        // value_eq(NULL, …) semantics, never the always-UNKNOWN
2463        // `x = NULL`; they translate — and push — in both modes.
2464        assert_eq!(
2465            export("/t/*[::x = null] | ::x").unwrap().query,
2466            "SELECT x FROM t WHERE x IS NULL"
2467        );
2468        assert_eq!(
2469            export("/t/*[::x != null] | ::x").unwrap().query,
2470            "SELECT x FROM t WHERE x IS NOT NULL"
2471        );
2472        assert_eq!(
2473            pushdown("/t/*[::x = null] | ::x", None).unwrap().sql,
2474            "SELECT x FROM t WHERE x IS NULL"
2475        );
2476        assert_eq!(
2477            pushdown("/t/*[::x != null] | ::x", None).unwrap().sql,
2478            "SELECT x FROM t WHERE x IS NOT NULL"
2479        );
2480    }
2481
2482    #[test]
2483    fn ne_and_not_refuse_pushdown_but_display_diverges() {
2484        // `!=` against a non-null value and `not(...)` drop the NULL
2485        // rows Quarb keeps under SQL three-valued logic: the pushdown
2486        // paths refuse (and scan), full and partial alike.
2487        assert!(pushdown("/t/*[::x != 5] | ::x", None).is_none());
2488        assert!(pushdown("/t/*[!::x = 5] | ::x", None).is_none());
2489        assert!(partial_pushdown(&format!("/t/*[::x != 5]{GROUPED}"), None).is_none());
2490        assert!(partial_pushdown(&format!("/t/*[!::x = 5]{GROUPED}"), None).is_none());
2491        // The display translation still emits `<>`, flagged with a note.
2492        let t = export("/t/*[::x != 5] | ::x").unwrap();
2493        assert_eq!(t.query, "SELECT x FROM t WHERE x <> 5");
2494        assert!(t.notes.iter().any(|n| n.contains("NULL")));
2495    }
2496
2497    #[test]
2498    fn unescapable_text_literal_refuses_pushdown() {
2499        // A backslash (MySQL/BigQuery escape) or an apostrophe
2500        // (BigQuery rejects '' doubling) has no portable escaping, so
2501        // pushdown refuses; a clean literal still pushes.
2502        assert!(pushdown("/files/*[::path = \"C:\\temp\"] | ::path", None).is_none());
2503        assert!(pushdown("/t/*[::name = \"it's\"] | ::name", None).is_none());
2504        assert!(partial_pushdown(&format!("/t/*[::name = \"it's\"]{GROUPED}"), None).is_none());
2505        assert_eq!(
2506            pushdown("/t/*[::name = \"rare\"] | ::name", None)
2507                .unwrap()
2508                .sql,
2509            "SELECT name FROM t WHERE name = 'rare'"
2510        );
2511    }
2512}