fv-streams-sql 0.6.0

The SQL front door for FusionVault Streams: a streaming SQL statement parses to a small typed logical plan and lowers to the same topology the TOML frontend produces — one runtime, two front doors. No DataFusion planner, no fork; expressions compile through the value dialect as the steps already do.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
//! The typed streaming **logical plan** — our own IR, the seam between the SQL front-end and the
//! `StageDef` lowering. Small and streaming-aware by construction (unlike DataFusion's `LogicalPlan`);
//! a future optimiser is a pass over this, and a second dialect is another producer of it.

use sqlparser::ast::{
    BinaryOperator, DateTimeField, DuplicateTreatment, Expr, Function, FunctionArg, FunctionArgExpr, FunctionArguments,
    GroupByExpr, JoinConstraint, JoinOperator, Query, Select, SelectItem, SetExpr, Statement, TableFactor,
    TableWithJoins, Value,
};
use sqlparser::dialect::GenericDialect;
use sqlparser::parser::Parser;

use crate::expr;

/// One projected output column.
#[derive(Debug, Clone, PartialEq)]
pub struct Proj {
    /// The output column name.
    pub out: String,
    /// `Some(dialect_expr)` when computed or renamed (lowers to an `applyExpression`); `None` for a
    /// bare pass-through column named `out` (kept by the `select`).
    pub expr: Option<String>,
}

/// One aggregate in a `SELECT` over a window — `op` over `column` (empty for `count(*)`), out `alias`.
#[derive(Debug, Clone, PartialEq)]
pub struct AggSpec {
    pub op: String,
    pub column: String,
    pub alias: String,
}

/// The windowing a `GROUP BY <window-fn>(…)` selects. An optional trailing `INTERVAL` on any window
/// function is the **allowed lateness** — how long a window stays open for late events after its end
/// (the engine's `allowedLatenessMs`); `None` leaves it at the engine default. q4/q5 need a large
/// lateness so no out-of-order bid is dropped from a closed window.
#[derive(Debug, Clone, PartialEq)]
pub enum Win {
    /// `TUMBLE(ts, INTERVAL <size> [, INTERVAL <lateness>])` — fixed windows.
    Tumble { size_ms: i64, lateness_ms: Option<i64> },
    /// `HOP(ts, INTERVAL <slide>, INTERVAL <size> [, INTERVAL <lateness>])` — sliding windows.
    Hop {
        slide_ms: i64,
        size_ms: i64,
        lateness_ms: Option<i64>,
    },
    /// `SESSION(ts, INTERVAL <gap> [, INTERVAL <lateness>])` — dynamic session windows.
    Session { gap_ms: i64, lateness_ms: Option<i64> },
}

/// The early-firing trigger a trailing `EMIT CHANGES EVERY …` clause selects — the 5a updating
/// aggregate. sqlparser does not know `EMIT`, so a small lexical pre-pass ([`split_emit`]) strips
/// and parses this clause before the rest of the statement reaches sqlparser (design §10 / A).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Trigger {
    EveryRows(u64),
    EveryMs(i64),
}

/// How a two-input `JOIN` maps to an operator. An interval predicate (`ts BETWEEN …`) in the `ON`
/// makes it a stream×stream interval join; a plain equi-join makes the right side a **bounded
/// table** — the 5b lookup join.
#[derive(Debug, Clone, PartialEq)]
pub enum JoinKind {
    /// `JOIN … ON k=k AND ts BETWEEN … ` → `streamJoin`.
    Interval { time_column: String, window_ms: i64 },
    /// `JOIN <bounded> ON k=k` → the 5b `lookupJoin` (right = the bounded table).
    Lookup,
}

/// The typed logical plan. 5c-i covers the stateless shape (source → filter → project → sink);
/// 5c-ii adds the windowed aggregate, the updating aggregate, and the joins.
#[derive(Debug, Clone, PartialEq)]
pub enum Plan {
    /// `FROM <dataset>` — a source dataset by name.
    Source(String),
    /// `FROM <left> JOIN <right> ON <key> [interval]` — a two-input join.
    Join {
        left: Box<Plan>,
        right: Box<Plan>,
        join_key: String,
        kind: JoinKind,
    },
    /// `WHERE <predicate>` — the predicate as a value-dialect string.
    Filter { input: Box<Plan>, predicate: String },
    /// `SELECT …`. `star` = `SELECT *` (pass-through, no step); else the projected columns.
    Project {
        input: Box<Plan>,
        star: bool,
        items: Vec<Proj>,
    },
    /// `SELECT … FROM … GROUP BY <window-fn>(ts,…), <keys>` — a windowed keyed aggregate. A
    /// `Some(trigger)` makes it the **5a updating aggregate** (early firing).
    Aggregate {
        input: Box<Plan>,
        time_column: String,
        window: Win,
        group_by: Vec<String>,
        /// Pre-aggregate computed columns (an aggregate's expression argument, e.g. a `CASE` fed to
        /// `count(DISTINCT …)`) — lowered to `applyExpression` steps BEFORE the aggregate.
        pre: Vec<Proj>,
        aggs: Vec<AggSpec>,
        /// Post-aggregate computed columns — a `SELECT` expression over the window/group/aggregates
        /// (e.g. `day = substring(epochToIso(windowStart), 0, 10)`), lowered to `applyExpression`
        /// steps AFTER the aggregate (the q15/q16 day/minute columns).
        post: Vec<Proj>,
        trigger: Option<Trigger>,
    },
    /// `SELECT … FROM (SELECT …, ROW_NUMBER() OVER (PARTITION BY g ORDER BY c [DESC]) AS rn FROM s)
    /// WHERE rn <= n` — the streaming top-N idiom → the `topN` operator.
    TopN {
        input: Box<Plan>,
        group_by: Vec<String>,
        order_by: String,
        /// A second `ORDER BY` column → the tie-break (`tieBy`, ascending).
        tie_by: Option<String>,
        descending: bool,
        n: usize,
    },
    /// A CTE (`WITH <name> AS (<subquery>)`): the sub-plan `input` materialises as its own stage
    /// under `name`, and downstream references to `name` read that stage. The multi-stage boundary —
    /// the SQL equivalent of a named intermediate dataset in the TOML `[[transforms]]` DAG.
    Named { name: String, input: Box<Plan> },
    /// `INSERT INTO <dataset>` — the terminal sink dataset by name.
    Sink { input: Box<Plan>, name: String },
}

/// Parse one streaming SQL statement into a [`Plan`]. Fails LOUDLY, streaming-aware, on anything
/// outside the supported subset.
pub fn parse(sql: &str) -> Result<Plan, String> {
    // Strip a trailing `EMIT CHANGES EVERY …` (sqlparser does not know it) before parsing the rest.
    let (sql, trigger) = split_emit(sql)?;
    let plan = parse_statement(&sql)?;
    match trigger {
        Some(t) => attach_trigger(plan, t),
        None => Ok(plan),
    }
}

fn parse_statement(sql: &str) -> Result<Plan, String> {
    let mut stmts = Parser::parse_sql(&GenericDialect {}, sql).map_err(|e| format!("SQL parse error: {e}"))?;
    if stmts.len() != 1 {
        return Err(format!("expected exactly one statement, got {}", stmts.len()));
    }
    match stmts.pop().expect("one") {
        Statement::Insert(insert) => {
            let sink = object_name(&insert.table.to_string());
            let query = insert
                .source
                .ok_or("INSERT INTO <sink> needs a SELECT (`INSERT INTO out SELECT …`)")?;
            let input = plan_query(&query)?;
            Ok(Plan::Sink {
                input: Box::new(input),
                name: sink,
            })
        }
        Statement::Query(_) => Err("a streaming statement must write to a sink: `INSERT INTO <sink> SELECT …`".into()),
        other => Err(format!(
            "unsupported statement `{}` — the supported shape is `INSERT INTO <sink> SELECT … FROM … [WHERE …]`",
            statement_kind(&other)
        )),
    }
}

fn plan_query(query: &Query) -> Result<Plan, String> {
    // `WITH name AS (subquery), …` — each CTE becomes a named intermediate stream (the multi-stage
    // boundary). SQL scoping: a CTE sees only the CTEs declared before it, so bodies are bound in
    // order against the ones already built; the outer body binds against all of them.
    let ctes = parse_ctes(query.with.as_ref())?;
    if query.order_by.is_some() {
        return Err("ORDER BY over an unbounded stream has no streaming meaning — use `ROW_NUMBER() OVER (PARTITION BY …) <= n` for a top-N".into());
    }
    if query.limit_clause.is_some() {
        return Err("LIMIT over an unbounded stream is not supported — use a top-N (`ROW_NUMBER() … <= n`)".into());
    }
    let select = match query.body.as_ref() {
        SetExpr::Select(s) => s.as_ref(),
        SetExpr::SetOperation { .. } => {
            return Err("UNION / INTERSECT / EXCEPT are not supported — express as separate pipelines".into())
        }
        _ => return Err("only a SELECT body is supported".into()),
    };
    Ok(bind_ctes(plan_select(select)?, &ctes))
}

/// Parse a `WITH` clause into `(name, plan)` in declaration order. Each CTE body is planned and then
/// bound against the CTEs declared before it (SQL scoping), so later stages can read earlier ones.
/// Recursive CTEs (`WITH RECURSIVE`) are not supported — there is no streaming fixpoint.
fn parse_ctes(with: Option<&sqlparser::ast::With>) -> Result<Vec<(String, Plan)>, String> {
    let Some(with) = with else { return Ok(Vec::new()) };
    if with.recursive {
        return Err("WITH RECURSIVE is not supported — a streaming CTE has no fixpoint".into());
    }
    let mut bound: Vec<(String, Plan)> = Vec::new();
    for cte in &with.cte_tables {
        let name = object_name(&cte.alias.name.value);
        let plan = bind_ctes(plan_query(&cte.query)?, &bound);
        bound.push((name, plan));
    }
    Ok(bound)
}

/// Replace every `Source(name)` that names a CTE with a `Named { name, <cte plan> }` boundary, so
/// lowering materialises it as its own stage. Recurses through the whole plan; a non-CTE `Source`
/// (a base dataset) is left untouched.
fn bind_ctes(plan: Plan, ctes: &[(String, Plan)]) -> Plan {
    if ctes.is_empty() {
        return plan;
    }
    let boxed = |p: Box<Plan>| Box::new(bind_ctes(*p, ctes));
    match plan {
        Plan::Source(name) => match ctes.iter().find(|(n, _)| *n == name) {
            Some((_, cte)) => Plan::Named {
                name,
                input: Box::new(cte.clone()),
            },
            None => Plan::Source(name),
        },
        Plan::Named { name, input } => Plan::Named {
            name,
            input: boxed(input),
        },
        Plan::Join {
            left,
            right,
            join_key,
            kind,
        } => Plan::Join {
            left: boxed(left),
            right: boxed(right),
            join_key,
            kind,
        },
        Plan::Filter { input, predicate } => Plan::Filter {
            input: boxed(input),
            predicate,
        },
        Plan::Project { input, star, items } => Plan::Project {
            input: boxed(input),
            star,
            items,
        },
        Plan::Aggregate {
            input,
            time_column,
            window,
            group_by,
            pre,
            aggs,
            post,
            trigger,
        } => Plan::Aggregate {
            input: boxed(input),
            time_column,
            window,
            group_by,
            pre,
            aggs,
            post,
            trigger,
        },
        Plan::TopN {
            input,
            group_by,
            order_by,
            tie_by,
            descending,
            n,
        } => Plan::TopN {
            input: boxed(input),
            group_by,
            order_by,
            tie_by,
            descending,
            n,
        },
        Plan::Sink { input, name } => Plan::Sink {
            input: boxed(input),
            name,
        },
    }
}

fn plan_select(select: &Select) -> Result<Plan, String> {
    // The ROW_NUMBER top-N idiom (a subquery + `WHERE rn <= n`) → the topN operator, projected by
    // the outer SELECT (the rank filter is consumed by the operator).
    if let Some(topn) = detect_topn(select)? {
        return parse_projection(topn, &select.projection);
    }

    // FROM: one table, optionally with one JOIN.
    if select.from.len() != 1 {
        return Err(format!(
            "expected one FROM item (comma joins are not supported — use `JOIN … ON …`), got {}",
            select.from.len()
        ));
    }
    let source = parse_from(&select.from[0])?;
    if select.having.is_some() {
        return Err("HAVING is not supported yet".into());
    }

    // WHERE → filter (reads the input columns, so it sits below the aggregate/projection).
    let filtered = match &select.selection {
        Some(pred) => Plan::Filter {
            input: Box::new(source),
            predicate: expr::to_dialect(pred)?,
        },
        None => source,
    };

    // GROUP BY <window-fn>(…), <keys> → a windowed keyed aggregate.
    let group_exprs = match &select.group_by {
        GroupByExpr::Expressions(exprs, _) if !exprs.is_empty() => Some(exprs.as_slice()),
        GroupByExpr::All(_) => return Err("GROUP BY ALL is not supported".into()),
        _ => None,
    };
    if let Some(gexprs) = group_exprs {
        return plan_aggregate(filtered, gexprs, &select.projection);
    }

    parse_projection(filtered, &select.projection)
}

/// The `SELECT` projection over an already-built input → a `Project` node.
fn parse_projection(input: Plan, projection: &[SelectItem]) -> Result<Plan, String> {
    let mut star = false;
    let mut items = Vec::new();
    for item in projection {
        match item {
            SelectItem::Wildcard(_) => star = true,
            SelectItem::UnnamedExpr(e) => {
                let out = column_name_of(e).ok_or("a projected expression needs an alias (`<expr> AS name`)")?;
                match e {
                    Expr::Identifier(_) | Expr::CompoundIdentifier(_) => items.push(Proj { out, expr: None }),
                    _ => items.push(Proj {
                        out,
                        expr: Some(expr::to_dialect(e)?),
                    }),
                }
            }
            SelectItem::ExprWithAlias { expr: e, alias } => {
                items.push(Proj {
                    out: alias.value.clone(),
                    expr: Some(expr::to_dialect(e)?),
                });
            }
            _ => return Err("`table.*` / multi-alias projections are not supported — list the columns".into()),
        }
    }
    if star && items.iter().any(|p| p.expr.is_none()) {
        return Err("`SELECT *, <bare column>` is redundant — `*` already keeps every column; with `*` add only computed columns (`*, <expr> AS name`)".into());
    }
    Ok(Plan::Project {
        input: Box::new(input),
        star,
        items,
    })
}

/// Recognise `FROM (SELECT …, ROW_NUMBER() OVER (PARTITION BY g ORDER BY c [DESC]) AS rn FROM s)
/// WHERE rn <= n` → a `TopN` over the inner source. `Ok(None)` when it is not that shape.
fn detect_topn(select: &Select) -> Result<Option<Plan>, String> {
    if select.from.len() != 1 || !select.from[0].joins.is_empty() {
        return Ok(None);
    }
    let TableFactor::Derived { subquery, .. } = &select.from[0].relation else {
        return Ok(None);
    };
    let SetExpr::Select(inner) = subquery.body.as_ref() else {
        return Ok(None);
    };
    // find ROW_NUMBER() OVER (…) AS <rn>
    let mut rn_fn = None;
    for item in &inner.projection {
        if let SelectItem::ExprWithAlias {
            expr: Expr::Function(f),
            alias,
        } = item
        {
            if f.name.to_string().eq_ignore_ascii_case("row_number") {
                rn_fn = Some((f, alias.value.clone()));
            }
        }
    }
    let Some((f, rn)) = rn_fn else { return Ok(None) }; // no ROW_NUMBER → not a top-N
    let Some(sqlparser::ast::WindowType::WindowSpec(ws)) = &f.over else {
        return Err("ROW_NUMBER() needs `OVER (PARTITION BY … ORDER BY …)`".into());
    };
    let group_by: Vec<String> = ws.partition_by.iter().filter_map(column_name_of).collect();
    let ob = ws
        .order_by
        .first()
        .ok_or("ROW_NUMBER() OVER needs an ORDER BY column")?;
    let order_by = column_name_of(&ob.expr).ok_or("ROW_NUMBER() ORDER BY must be a column")?;
    let descending = ob.options.asc == Some(false); // DESC
                                                    // a second ORDER BY column is the tie-break (ascending, like the operator's `tieBy`).
    let tie_by = match ws.order_by.get(1) {
        Some(t) => Some(column_name_of(&t.expr).ok_or("ROW_NUMBER() tie-break must be a column")?),
        None => None,
    };
    if inner.from.len() != 1 || !inner.from[0].joins.is_empty() {
        return Err("the ROW_NUMBER subquery must read exactly one source".into());
    }
    let source = table_source(&inner.from[0].relation)?;
    // the subquery's WHERE (e.g. `type = 'bid'`) filters before the rank.
    let input = match &inner.selection {
        Some(pred) => Plan::Filter {
            input: Box::new(source),
            predicate: expr::to_dialect(pred)?,
        },
        None => source,
    };
    let n = rank_limit(select.selection.as_ref(), &rn)?;
    Ok(Some(Plan::TopN {
        input: Box::new(input),
        group_by,
        order_by,
        tie_by,
        descending,
        n,
    }))
}

/// The `n` from an outer `WHERE <rn> <= n` (or `<rn> = 1`) top-N filter.
fn rank_limit(where_: Option<&Expr>, rn: &str) -> Result<usize, String> {
    let e = where_.ok_or_else(|| format!("a ROW_NUMBER top-N needs an outer `WHERE {rn} <= n`"))?;
    let is_rn = |x: &Expr| column_name_of(x).as_deref() == Some(rn);
    match e {
        Expr::BinaryOp {
            left,
            op: BinaryOperator::LtEq,
            right,
        } if is_rn(left) => literal_usize(right),
        Expr::BinaryOp {
            left,
            op: BinaryOperator::Eq,
            right,
        } if is_rn(left) => match literal_usize(right)? {
            1 => Ok(1),
            _ => Err("a `= n` top-N filter only supports n = 1 — use `<= n`".into()),
        },
        _ => Err(format!("the top-N filter must be `{rn} <= n`")),
    }
}

fn literal_usize(e: &Expr) -> Result<usize, String> {
    match e {
        Expr::Value(v) => match &v.value {
            Value::Number(s, _) => s.trim().parse().map_err(|_| format!("`{s}` is not a whole number")),
            other => Err(format!("expected a number, got `{other}`")),
        },
        other => Err(format!("expected a number, got `{other}`")),
    }
}

/// `GROUP BY <window-fn>(ts,…), <keys>` + aggregate projections → a windowed keyed aggregate.
fn plan_aggregate(input: Plan, group_exprs: &[Expr], projection: &[SelectItem]) -> Result<Plan, String> {
    let mut window: Option<(String, Win)> = None;
    let mut group_by = Vec::new();
    for g in group_exprs {
        match g {
            Expr::Function(f) if is_window_fn(f) => {
                if window.is_some() {
                    return Err("only one window function may appear in GROUP BY".into());
                }
                window = Some(parse_window_fn(f)?);
            }
            Expr::Identifier(id) => group_by.push(id.value.clone()),
            Expr::CompoundIdentifier(p) => group_by.push(p.last().expect("non-empty").value.clone()),
            other => {
                return Err(format!(
                    "unsupported GROUP BY item `{other}` — a window function (`TUMBLE/HOP/SESSION`) or a plain column"
                ))
            }
        }
    }
    let (time_column, window) = window.ok_or(
        "a streaming GROUP BY needs a window: `GROUP BY TUMBLE/HOP/SESSION(ts, INTERVAL …)` (an unbounded aggregate needs `… EMIT CHANGES` — the 5a updating aggregate)",
    )?;
    let (pre, aggs, post) = parse_agg_select(projection)?;
    if aggs.is_empty() {
        return Err("a windowed GROUP BY needs at least one aggregate in SELECT (count/sum/avg/min/max)".into());
    }
    Ok(Plan::Aggregate {
        input: Box::new(input),
        time_column,
        window,
        group_by,
        pre,
        aggs,
        post,
        trigger: None,
    })
}

/// Strip a trailing `EMIT CHANGES EVERY <n> ROWS|MS` clause (case-insensitive, outside string
/// literals). Returns the SQL without it and the parsed trigger, if any.
fn split_emit(sql: &str) -> Result<(String, Option<Trigger>), String> {
    let lower = sql.to_ascii_lowercase();
    let bytes = lower.as_bytes();
    let is_word = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
    let mut in_str = false;
    let mut at = None;
    let mut i = 0usize;
    while i < bytes.len() {
        if bytes[i] == b'\'' {
            in_str = !in_str;
            i += 1;
            continue;
        }
        if !in_str
            && lower[i..].starts_with("emit")
            && (i == 0 || !is_word(bytes[i - 1]))
            && (i + 4 >= bytes.len() || !is_word(bytes[i + 4]))
        {
            at = Some(i); // the last unquoted `emit` wins (it is a trailing clause)
        }
        i += 1;
    }
    let Some(at) = at else {
        return Ok((sql.to_string(), None));
    };
    let head = sql[..at].trim_end().to_string();
    let trigger = parse_emit(&sql[at..])?;
    Ok((head, Some(trigger)))
}

fn parse_emit(clause: &str) -> Result<Trigger, String> {
    let toks: Vec<String> = clause.split_whitespace().map(|s| s.to_ascii_lowercase()).collect();
    let shape = "`EMIT CHANGES EVERY <n> ROWS` or `EMIT CHANGES EVERY <n> MS`";
    if toks.len() < 2 || toks[0] != "emit" || toks[1] != "changes" {
        return Err(format!("unrecognised EMIT clause — use {shape}"));
    }
    if toks.len() == 2 {
        return Err(format!("`EMIT CHANGES` needs a cadence: {shape}"));
    }
    if toks.len() != 5 || toks[2] != "every" {
        return Err(format!("EMIT clause: expected {shape}"));
    }
    let n: u64 = toks[3]
        .parse()
        .map_err(|_| format!("EMIT cadence `{}` is not a whole number", toks[3]))?;
    match toks[4].as_str() {
        "rows" | "row" => Ok(Trigger::EveryRows(n)),
        "ms" | "milliseconds" | "millisecond" => Ok(Trigger::EveryMs(n as i64)),
        other => Err(format!("EMIT cadence unit `{other}` — use ROWS or MS")),
    }
}

/// Attach a trigger to the plan's windowed aggregate (the 5a updating aggregate). The trigger is
/// valid only on a windowed (`TUMBLE`/`HOP`) aggregate — the operator that early-fires.
fn attach_trigger(plan: Plan, trigger: Trigger) -> Result<Plan, String> {
    match plan {
        Plan::Sink { input, name } => Ok(Plan::Sink {
            input: Box::new(attach_trigger(*input, trigger)?),
            name,
        }),
        Plan::Aggregate {
            input,
            time_column,
            window,
            group_by,
            pre,
            aggs,
            post,
            trigger: _,
        } => {
            if matches!(window, Win::Session { .. }) {
                return Err("EMIT CHANGES is supported on windowed aggregates (TUMBLE / HOP), not sessions".into());
            }
            Ok(Plan::Aggregate {
                input,
                time_column,
                window,
                group_by,
                pre,
                aggs,
                post,
                trigger: Some(trigger),
            })
        }
        _ => Err("EMIT CHANGES needs a windowed GROUP BY aggregate (`GROUP BY <keys>, TUMBLE(ts, INTERVAL …)`)".into()),
    }
}

fn is_window_fn(f: &Function) -> bool {
    matches!(f.name.to_string().to_uppercase().as_str(), "TUMBLE" | "HOP" | "SESSION")
}

/// `TUMBLE(ts, INTERVAL <size>)` / `HOP(ts, INTERVAL <slide>, INTERVAL <size>)` /
/// `SESSION(ts, INTERVAL <gap>)` → (event-time column, window).
fn parse_window_fn(f: &Function) -> Result<(String, Win), String> {
    let name = f.name.to_string().to_uppercase();
    let args = fn_args(f)?;
    let time_col = |e: &Expr| -> Result<String, String> {
        match e {
            Expr::Identifier(id) => Ok(id.value.clone()),
            Expr::CompoundIdentifier(p) => Ok(p.last().expect("non-empty").value.clone()),
            _ => Err(format!("{name}(…)'s first argument must be the event-time column")),
        }
    };
    // an optional trailing INTERVAL beyond the base arity is the allowed lateness.
    let lateness = |base: usize| -> Result<Option<i64>, String> {
        match args.len() {
            n if n == base => Ok(None),
            n if n == base + 1 => Ok(Some(interval_ms(args[base])?)),
            _ => Err(String::new()), // arity handled by the arm guards below
        }
    };
    match name.as_str() {
        "TUMBLE" if args.len() == 2 || args.len() == 3 => Ok((
            time_col(args[0])?,
            Win::Tumble {
                size_ms: interval_ms(args[1])?,
                lateness_ms: lateness(2)?,
            },
        )),
        "HOP" if args.len() == 3 || args.len() == 4 => Ok((
            time_col(args[0])?,
            Win::Hop {
                slide_ms: interval_ms(args[1])?,
                size_ms: interval_ms(args[2])?,
                lateness_ms: lateness(3)?,
            },
        )),
        "SESSION" if args.len() == 2 || args.len() == 3 => Ok((
            time_col(args[0])?,
            Win::Session {
                gap_ms: interval_ms(args[1])?,
                lateness_ms: lateness(2)?,
            },
        )),
        "TUMBLE" | "SESSION" => Err(format!(
            "{name}(ts, INTERVAL <size> [, INTERVAL <lateness>]) takes 2 or 3 arguments"
        )),
        "HOP" => {
            Err("HOP(ts, INTERVAL <slide>, INTERVAL <size> [, INTERVAL <lateness>]) takes 3 or 4 arguments".into())
        }
        other => Err(format!("unsupported window function `{other}`")),
    }
}

fn is_agg_name(name: &str) -> bool {
    matches!(name, "count" | "sum" | "avg" | "min" | "max")
}

/// Classify a windowed `SELECT`'s projections: aggregate calls (→ `aggs`, with any expression
/// arguments hoisted to `pre` computed columns), bare group columns (skipped — GROUP BY captured
/// them), and other computed columns over the window/group/aggregates (→ `post` applyExpression
/// steps after the aggregate, e.g. `day = substring(epochToIso(windowStart), 0, 10)`).
#[allow(clippy::type_complexity)]
fn parse_agg_select(projection: &[SelectItem]) -> Result<(Vec<Proj>, Vec<AggSpec>, Vec<Proj>), String> {
    let mut pre: Vec<Proj> = Vec::new();
    let mut aggs = Vec::new();
    let mut post: Vec<Proj> = Vec::new();
    for item in projection {
        let (e, alias) = match item {
            SelectItem::ExprWithAlias { expr, alias } => (expr, Some(alias.value.clone())),
            SelectItem::UnnamedExpr(e) => (e, None),
            SelectItem::Wildcard(_) => return Err("`SELECT *` is not allowed with GROUP BY".into()),
            _ => return Err("unsupported projection in a GROUP BY query".into()),
        };
        match e {
            Expr::Function(f) if is_agg_name(&f.name.to_string().to_lowercase()) => {
                aggs.push(agg_of(f, alias, &mut pre)?);
            }
            // a bare group column — already in the aggregate's output.
            Expr::Identifier(_) | Expr::CompoundIdentifier(_) => {}
            // a computed column over the window/group/aggregates → a post-aggregate applyExpression.
            _ => {
                let out =
                    alias.ok_or("a computed SELECT column in a GROUP BY query needs an alias (`<expr> AS name`)")?;
                post.push(Proj {
                    out,
                    expr: Some(expr::to_dialect(e)?),
                });
            }
        }
    }
    Ok((pre, aggs, post))
}

fn agg_of(f: &Function, alias: Option<String>, pre: &mut Vec<Proj>) -> Result<AggSpec, String> {
    let name = f.name.to_string().to_lowercase();
    let alias = alias.ok_or_else(|| format!("aggregate `{name}(…)` needs an alias (`{name}(…) AS name`)"))?;
    let distinct = matches!(
        &f.args,
        FunctionArguments::List(l) if l.duplicate_treatment == Some(DuplicateTreatment::Distinct)
    );
    let op = match (name.as_str(), distinct) {
        ("count", false) => "count",
        ("count", true) => "countDistinct",
        ("sum", false) => "sum",
        ("avg", false) => "avg",
        ("min", false) => "min",
        ("max", false) => "max",
        (other, true) => return Err(format!("DISTINCT is only supported on `count()`, not `{other}()`")),
        (other, false) => {
            return Err(format!(
                "unsupported aggregate `{other}` — count/sum/avg/min/max/count(DISTINCT …)"
            ))
        }
    };
    let args = fn_args(f)?;
    // count(*) has no column; a bare column feeds the aggregate directly; an EXPRESSION argument
    // (CASE, arithmetic) becomes a synthetic pre-aggregate column (the q15/q16 null-mask shape).
    let column = match args.first() {
        None => String::new(),
        Some(Expr::Identifier(id)) => id.value.clone(),
        Some(Expr::CompoundIdentifier(p)) => p.last().expect("non-empty").value.clone(),
        Some(other) => {
            let synth = format!("_fv_agg{}", pre.len());
            pre.push(Proj {
                out: synth.clone(),
                expr: Some(expr::to_dialect(other)?),
            });
            synth
        }
    };
    Ok(AggSpec {
        op: op.to_string(),
        column,
        alias,
    })
}

/// The plain `Expr` arguments of a function call (a `*` wildcard contributes none — `count(*)`).
fn fn_args(f: &Function) -> Result<Vec<&Expr>, String> {
    let list = match &f.args {
        FunctionArguments::List(l) => &l.args,
        FunctionArguments::None => return Ok(Vec::new()),
        FunctionArguments::Subquery(_) => return Err("subquery arguments are not supported".into()),
    };
    let mut out = Vec::new();
    for a in list {
        match a {
            FunctionArg::Unnamed(FunctionArgExpr::Expr(e)) => out.push(e),
            FunctionArg::Unnamed(FunctionArgExpr::Wildcard) => {}
            _ => return Err("unsupported function argument (named / qualified wildcard)".into()),
        }
    }
    Ok(out)
}

/// An `INTERVAL '<n>' <unit>` as milliseconds.
fn interval_ms(e: &Expr) -> Result<i64, String> {
    let Expr::Interval(iv) = e else {
        return Err(format!("expected an INTERVAL (e.g. `INTERVAL '10' SECOND`), got `{e}`"));
    };
    let n: i64 = match iv.value.as_ref() {
        Expr::Value(v) => match &v.value {
            Value::SingleQuotedString(s) | Value::Number(s, _) => s
                .trim()
                .parse()
                .map_err(|_| format!("interval value `{s}` is not an integer"))?,
            other => return Err(format!("unsupported interval value `{other}`")),
        },
        other => return Err(format!("unsupported interval value `{other}`")),
    };
    let unit = match &iv.leading_field {
        Some(DateTimeField::Millisecond) => 1,
        Some(DateTimeField::Second) => 1_000,
        Some(DateTimeField::Minute) => 60_000,
        Some(DateTimeField::Hour) => 3_600_000,
        Some(DateTimeField::Day) => 86_400_000,
        other => {
            return Err(format!(
                "unsupported interval unit `{other:?}` — use MILLISECOND / SECOND / MINUTE / HOUR / DAY"
            ))
        }
    };
    Ok(n * unit)
}

/// `FROM <left> [JOIN <right> ON …]` → a `Source` or a `Join`.
fn parse_from(twj: &TableWithJoins) -> Result<Plan, String> {
    let left = table_source(&twj.relation)?;
    match twj.joins.len() {
        0 => Ok(left),
        1 => {
            let j = &twj.joins[0];
            let right = table_source(&j.relation)?;
            let (join_key, kind) = parse_join_operator(&j.join_operator)?;
            Ok(Plan::Join {
                left: Box::new(left),
                right: Box::new(right),
                join_key,
                kind,
            })
        }
        _ => Err("only a single JOIN is supported".into()),
    }
}

fn table_source(tf: &TableFactor) -> Result<Plan, String> {
    match tf {
        TableFactor::Table { name, .. } => Ok(Plan::Source(object_name(&name.to_string()))),
        other => Err(format!("unsupported FROM item `{other}` — a plain dataset name")),
    }
}

/// `JOIN … ON a.k = b.k [AND ts BETWEEN … ]` → (join key, kind). An interval predicate makes it a
/// stream×stream interval join; without one, the right side is a bounded table (the 5b lookup join).
fn parse_join_operator(op: &JoinOperator) -> Result<(String, JoinKind), String> {
    let on = match op {
        JoinOperator::Inner(JoinConstraint::On(e)) | JoinOperator::Join(JoinConstraint::On(e)) => e,
        _ => return Err("only `INNER JOIN … ON <a.k = b.k> [AND <ts> BETWEEN …]` is supported".into()),
    };
    let mut join_key: Option<String> = None;
    let mut interval: Option<(String, i64)> = None;
    for c in split_and(on) {
        match c {
            Expr::BinaryOp {
                left,
                op: BinaryOperator::Eq,
                right,
            } => {
                join_key = Some(same_column(left, right)?);
            }
            Expr::Between {
                expr,
                negated: false,
                low,
                high,
            } => {
                interval = Some(between_interval(expr, low, high)?);
            }
            other => {
                return Err(format!(
                    "unsupported JOIN ON predicate `{other}` — an equi-key `a.k = b.k` and optionally `ts BETWEEN …`"
                ))
            }
        }
    }
    let join_key = join_key.ok_or("JOIN ON needs an equi-key (`a.k = b.k`, same column name on both sides)")?;
    let kind = match interval {
        Some((time_column, window_ms)) => JoinKind::Interval { time_column, window_ms },
        None => JoinKind::Lookup,
    };
    Ok((join_key, kind))
}

/// Flatten an `AND` chain into its conjuncts.
fn split_and(e: &Expr) -> Vec<&Expr> {
    match e {
        Expr::BinaryOp {
            left,
            op: BinaryOperator::And,
            right,
        } => {
            let mut v = split_and(left);
            v.extend(split_and(right));
            v
        }
        Expr::Nested(inner) => split_and(inner),
        other => vec![other],
    }
}

/// `a.k = b.k` → `k`. The two sides must name the SAME column (the join key present on both inputs).
fn same_column(l: &Expr, r: &Expr) -> Result<String, String> {
    let lc = column_name_of(l);
    let rc = column_name_of(r);
    match (lc, rc) {
        (Some(a), Some(b)) if a == b => Ok(a),
        (Some(a), Some(b)) => Err(format!(
            "the JOIN key columns must share a name (`{a}` vs `{b}`) — rename one upstream"
        )),
        _ => Err("JOIN key must be `a.col = b.col` (plain columns)".into()),
    }
}

/// `ts BETWEEN b.ts - INTERVAL … AND b.ts + INTERVAL …` → (event-time column, window ms).
fn between_interval(expr: &Expr, low: &Expr, high: &Expr) -> Result<(String, i64), String> {
    let time_column = column_name_of(expr)
        .ok_or("the interval join's BETWEEN must be over an event-time column (`a.ts BETWEEN …`)")?;
    // the window is the magnitude of the interval on either bound (symmetric ±window).
    let ms = interval_in(high).or_else(|_| interval_in(low))?;
    Ok((time_column, ms))
}

/// Find an `INTERVAL` inside a bound like `b.ts + INTERVAL '5' SECOND` and return it in ms.
fn interval_in(e: &Expr) -> Result<i64, String> {
    match e {
        Expr::Interval(_) => interval_ms(e),
        Expr::BinaryOp { left, right, .. } => interval_in(right).or_else(|_| interval_in(left)),
        Expr::Nested(inner) => interval_in(inner),
        _ => Err("the interval join's BETWEEN needs an `INTERVAL` bound (`b.ts + INTERVAL '5' SECOND`)".into()),
    }
}

/// The output name a bare projected expression takes (a column keeps its own name; a compound
/// `a.b` takes `b`). `None` for a computed expression that needs an explicit alias.
fn column_name_of(e: &Expr) -> Option<String> {
    match e {
        Expr::Identifier(id) => Some(id.value.clone()),
        Expr::CompoundIdentifier(parts) => parts.last().map(|p| p.value.clone()),
        _ => None,
    }
}

/// An object name (`schema.name` → `name`) reduced to the last part — datasets are referenced by a
/// single name in the pipeline config.
fn object_name(raw: &str) -> String {
    raw.rsplit('.').next().unwrap_or(raw).trim_matches('"').to_string()
}

fn statement_kind(s: &Statement) -> &'static str {
    match s {
        Statement::Insert(_) => "INSERT",
        Statement::Query(_) => "SELECT",
        Statement::CreateTable(_) => "CREATE TABLE",
        _ => "statement",
    }
}