syntaqlite-cli 0.5.6

Fast, accurate SQLite SQL formatter, validator, and language server — built on SQLite's own grammar
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
// Copyright 2025 The syntaqlite Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0.

//! `serve json` — long-lived JSON RPC server over stdio.
//!
//! The Python bindings spawn `syntaqlite serve json` once and multiplex all
//! parse/format/tokenize/validate calls over a single subprocess, amortizing
//! process startup and dialect initialization across a session.
//!
//! ## Protocol
//!
//! On startup, the server writes `READY\n` to stdout, then reads requests in
//! a loop until the client sends `{"op":"quit"}` or closes stdin.
//!
//! **Request:** one JSON object per line (newline-terminated, no embedded newlines).
//! **Response:** one JSON object per line — `{"ok":true,"result":<value>}` on
//! success, `{"ok":false,"error":<string>}` on failure.
//!
//! Ops:
//!
//! - `{"op":"parse","sql":"..."}` →
//!   `{"statements":[<AST JSON>,...],"errors":[<diag>,...]}`.
//!   AST shape matches `serde_json::to_value(AnyNode)` — see `syntaqlite parse -o json`.
//! - `{"op":"format","sql":"...","line_width"?:int,"indent_width"?:int,"keyword_case"?:"upper"|"lower","semicolons"?:bool}` →
//!   `{"formatted":"..."}`.
//! - `{"op":"tokenize","sql":"..."}` →
//!   `{"tokens":[{"text","offset","length","type","category"},...]}`.
//! - `{"op":"analyze","sql":"...","tables"?:[...],"views"?:[...],"schema_ddl"?:"...","render"?:bool}` →
//!   `{"diagnostics":[...],"statements":[...],"lineage":<lineage>|null}` (or `{"rendered":"..."}` when `render=true`).
//! - `{"op":"quit"}` → server exits cleanly without a response.
//!
//! Response values are built from borrowed `Serialize` views where possible
//! so the hot paths don't allocate intermediate `Vec<Value>` trees.

use std::collections::HashMap;
use std::io::{self, BufRead, BufReader, Write};
use std::ops::Deref;

use serde::{Deserialize, Serialize, ser::SerializeSeq};
use serde_json::Value;
use syntaqlite::Diagnostic;
use syntaqlite::analysis::{
    CatalogLayer, DiagnosticMessage, Help, ModuleResolver, RelationKind, Severity as SemSeverity,
    StatementAnalysis,
};
use syntaqlite::any::{AnyDialect, AnyParser, AnyTokenizer, ParseOutcome};
use syntaqlite::fmt::KeywordCase;
use syntaqlite::util::DiagnosticRenderer;
use syntaqlite::{AnalysisConfig, AnalysisContext, Analyzer, Catalog, FormatConfig, Formatter};

pub(crate) fn run(dialect: &AnyDialect) -> Result<(), String> {
    let stdin = io::stdin();
    let stdout = io::stdout();
    let mut reader = BufReader::new(stdin.lock());
    let mut writer = io::BufWriter::new(stdout.lock());

    writeln!(writer, "READY").map_err(|e| format!("write READY: {e}"))?;
    writer.flush().map_err(|e| format!("flush READY: {e}"))?;

    // Long-lived workers reused across all requests in this session. Parser,
    // tokenizer, and analyzer are stateless between requests; the Formatter
    // cache keeps the per-config one alive so its internal arenas and
    // render buffers survive across format calls with the same config.
    let parser = AnyParser::new(dialect.deref().clone());
    let tokenizer = AnyTokenizer::new(dialect.deref().clone());
    let mut analyzer = Analyzer::with_dialect(dialect.clone());
    let mut formatter_cache: Option<(FormatConfig, Formatter)> = None;

    let mut line = String::new();
    loop {
        line.clear();
        let n = reader
            .read_line(&mut line)
            .map_err(|e| format!("read: {e}"))?;
        if n == 0 {
            return Ok(()); // EOF
        }
        let trimmed = line.trim_end_matches(['\n', '\r']);
        if trimmed.is_empty() {
            continue;
        }

        let req: Value = match serde_json::from_str(trimmed) {
            Ok(v) => v,
            Err(e) => {
                write_err(&mut writer, &format!("invalid JSON: {e}"))?;
                continue;
            }
        };
        let Some(op) = req.get("op").and_then(Value::as_str) else {
            write_err(&mut writer, "missing \"op\" field")?;
            continue;
        };

        if op == "quit" {
            return Ok(());
        }

        let outcome = match op {
            "parse" => handle_parse(&parser, &req).and_then(|r| write_ok(&mut writer, &r)),
            "format" => handle_format(dialect, &mut formatter_cache, &req)
                .and_then(|r| write_ok(&mut writer, &r)),
            "tokenize" => {
                handle_tokenize(dialect, &tokenizer, &req).and_then(|r| write_ok(&mut writer, &r))
            }
            "analyze" => handle_analyze(dialect, &mut analyzer, &req, &mut writer),
            other => Err(format!("unknown op: {other}")),
        };

        if let Err(msg) = outcome {
            write_err(&mut writer, &msg)?;
        }
    }
}

// ── framing ──────────────────────────────────────────────────────────────

#[derive(Serialize)]
struct OkFrame<'a, T: Serialize> {
    ok: bool,
    result: &'a T,
}

#[derive(Serialize)]
struct ErrFrame<'a> {
    ok: bool,
    error: &'a str,
}

fn write_ok<W: Write, T: Serialize>(w: &mut W, result: &T) -> Result<(), String> {
    let frame = OkFrame { ok: true, result };
    serde_json::to_writer(&mut *w, &frame).map_err(|e| format!("write: {e}"))?;
    w.write_all(b"\n").map_err(|e| format!("write: {e}"))?;
    w.flush().map_err(|e| format!("flush: {e}"))
}

fn write_err<W: Write>(w: &mut W, msg: &str) -> Result<(), String> {
    let frame = ErrFrame {
        ok: false,
        error: msg,
    };
    serde_json::to_writer(&mut *w, &frame).map_err(|e| format!("write: {e}"))?;
    w.write_all(b"\n").map_err(|e| format!("write: {e}"))?;
    w.flush().map_err(|e| format!("flush: {e}"))
}

// ── parse ────────────────────────────────────────────────────────────────

#[derive(Deserialize)]
struct ParseReq {
    sql: String,
}

#[derive(Serialize)]
struct ParseResp {
    statements: Vec<Value>,
    errors: Vec<ParseErrView>,
}

#[derive(Serialize)]
struct ParseErrView {
    severity: &'static str,
    message: String,
    start_offset: usize,
    end_offset: usize,
    code: u32,
}

fn handle_parse(parser: &AnyParser, req: &Value) -> Result<ParseResp, String> {
    let req: ParseReq = serde_json::from_value(req.clone()).map_err(|e| format!("parse: {e}"))?;
    let mut session = parser.parse(&req.sql);
    // Statements are buffered as `Value` because they borrow from the session
    // arena and we can't serialize them lazily while also iterating `session`.
    let mut statements: Vec<Value> = Vec::new();
    let mut errors: Vec<ParseErrView> = Vec::new();
    loop {
        match session.next() {
            ParseOutcome::Ok(stmt) => {
                let erased = stmt.erase();
                let node = erased
                    .root_node()
                    .and_then(|n| serde_json::to_value(n).ok())
                    .unwrap_or(Value::Null);
                statements.push(node);
            }
            ParseOutcome::Err(err) => {
                let base = err.statement_base();
                let stmt_offset = err.offset().unwrap_or_default();
                let length = err.length().unwrap_or_default();
                let start = stmt_offset.to_doc(base).as_usize();
                errors.push(ParseErrView {
                    severity: "error",
                    message: err.message().to_string(),
                    start_offset: start,
                    end_offset: start + length.as_usize(),
                    code: DIAG_CODE_PARSE_ERROR,
                });
            }
            ParseOutcome::Done => break,
        }
    }
    Ok(ParseResp { statements, errors })
}

// ── format ───────────────────────────────────────────────────────────────

#[derive(Deserialize)]
struct FormatReq {
    sql: String,
    line_width: Option<usize>,
    indent_width: Option<usize>,
    keyword_case: Option<String>,
    semicolons: Option<bool>,
}

#[derive(Serialize)]
struct FormatResp {
    formatted: String,
}

fn handle_format(
    dialect: &AnyDialect,
    cache: &mut Option<(FormatConfig, Formatter)>,
    req: &Value,
) -> Result<FormatResp, String> {
    let req: FormatReq = serde_json::from_value(req.clone()).map_err(|e| format!("format: {e}"))?;
    let mut config = FormatConfig::default();
    if let Some(w) = req.line_width {
        config = config.with_line_width(w);
    }
    if let Some(w) = req.indent_width {
        config = config.with_indent_width(w);
    }
    if let Some(case) = req.keyword_case.as_deref() {
        let kc = match case {
            "upper" => KeywordCase::Upper,
            "lower" => KeywordCase::Lower,
            other => {
                return Err(format!(
                    "keyword_case must be 'upper' or 'lower', got {other:?}"
                ));
            }
        };
        config = config.with_keyword_case(kc);
    }
    if let Some(s) = req.semicolons {
        config = config.with_semicolons(s);
    }

    // Reuse the cached formatter when its config matches — its arenas and
    // render buffers survive across calls. On a config change (rare in
    // practice) rebuild once and cache the new one.
    let formatter = match cache {
        Some((cfg, f)) if format_config_eq(cfg, &config) => f,
        slot => {
            *slot = Some((
                config.clone(),
                Formatter::with_dialect_config(dialect.clone(), &config),
            ));
            &mut slot.as_mut().expect("just inserted").1
        }
    };
    formatter
        .format(&req.sql)
        .map(|formatted| FormatResp { formatted })
        .map_err(|e| format!("{e}"))
}

fn format_config_eq(a: &FormatConfig, b: &FormatConfig) -> bool {
    a.line_width() == b.line_width()
        && a.indent_width() == b.indent_width()
        && a.keyword_case() == b.keyword_case()
        && a.semicolons() == b.semicolons()
}

// ── tokenize ─────────────────────────────────────────────────────────────

#[derive(Serialize)]
struct TokenizeResp<'a> {
    tokens: TokensView<'a>,
}

/// Serializes the tokenizer iterator directly into a JSON array without
/// collecting into an intermediate `Vec`.
struct TokensView<'a> {
    dialect: &'a AnyDialect,
    tokenizer: &'a AnyTokenizer,
    sql: &'a str,
}

impl Serialize for TokensView<'_> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let base = self.sql.as_ptr() as usize;
        // `size_hint` isn't available; emit without a known length.
        let mut seq = serializer.serialize_seq(None)?;
        for tok in self.tokenizer.tokenize(self.sql) {
            let text = tok.text();
            let offset = (text.as_ptr() as usize).saturating_sub(base);
            let length = text.len();
            let tt = tok.token_type();
            seq.serialize_element(&TokenView {
                text,
                offset,
                length,
                token_type: u32::from(tt),
                category: token_category_name(self.dialect.token_category(tt)),
            })?;
        }
        seq.end()
    }
}

#[derive(Serialize)]
struct TokenView<'a> {
    text: &'a str,
    offset: usize,
    length: usize,
    #[serde(rename = "type")]
    token_type: u32,
    category: &'static str,
}

fn handle_tokenize<'a>(
    dialect: &'a AnyDialect,
    tokenizer: &'a AnyTokenizer,
    req: &'a Value,
) -> Result<TokenizeResp<'a>, String> {
    let sql = req
        .get("sql")
        .and_then(Value::as_str)
        .ok_or_else(|| "tokenize: missing 'sql'".to_string())?;
    Ok(TokenizeResp {
        tokens: TokensView {
            dialect,
            tokenizer,
            sql,
        },
    })
}

fn token_category_name(c: syntaqlite_syntax::any::TokenCategory) -> &'static str {
    use syntaqlite_syntax::any::TokenCategory as T;
    match c {
        T::Keyword => "keyword",
        T::Identifier => "identifier",
        T::String => "string",
        T::Number => "number",
        T::Operator => "operator",
        T::Punctuation => "punctuation",
        T::Comment => "comment",
        T::Parameter => "parameter",
        T::Function => "function",
        T::Type => "type",
        T::Other => "other",
    }
}

// ── validate ─────────────────────────────────────────────────────────────

#[derive(Deserialize)]
struct TableRec {
    name: String,
    columns: Option<Vec<String>>,
}

#[derive(Deserialize)]
struct ViewRec {
    name: String,
    columns: Option<Vec<String>>,
}

#[derive(Deserialize)]
struct ValidateReq {
    sql: String,
    tables: Option<Vec<TableRec>>,
    views: Option<Vec<ViewRec>>,
    schema_ddl: Option<String>,
    /// Optional map of dotted module path → SQL source, used to resolve
    /// `INCLUDE MODULE` imports. Callers must supply every module they
    /// expect to be referenced (transitively). Programmatic / lazy
    /// resolution is tracked in `docs/python-rpc-module-resolver-plan.md`.
    modules: Option<HashMap<String, String>>,
    /// Output format: `"structured"` (default) returns a typed result
    /// object; `"text"` returns rendered diagnostics.
    output: Option<String>,
    /// Per-call render options (only honoured when `output == "text"`).
    render_options: Option<RenderOptions>,
}

#[derive(Deserialize, Default)]
struct RenderOptions {
    /// Source label shown in rendered diagnostics (analogous to a file path).
    /// Defaults to the empty string.
    #[serde(default)]
    source_name: String,
}

/// Construct the [`ModuleResolver`] for this request, if any.
///
/// This is the single seam where we pick a resolver strategy. Today the
/// only strategy is [`HashMapResolver`] driven by the request's `modules`
/// field (eager dict). Future strategies (e.g. bidirectional callbacks)
/// plug in here.
fn build_module_resolver(req: &ValidateReq) -> Option<Box<dyn ModuleResolver>> {
    let modules = req.modules.as_ref()?;
    if modules.is_empty() {
        return None;
    }
    Some(Box::new(HashMapResolver(modules.clone())))
}

/// A `ModuleResolver` that looks up a dotted module path in an in-memory map.
struct HashMapResolver(HashMap<String, String>);

impl ModuleResolver for HashMapResolver {
    fn resolve(&self, module_path: &str) -> Option<String> {
        self.0.get(module_path).cloned()
    }
}

#[derive(Serialize)]
struct RenderedResp {
    rendered: String,
}

/// The full validate response. All child views borrow from the
/// `Analysis`, so serialization is a single walk with zero
/// intermediate `Vec<Value>` allocations.
#[derive(Serialize)]
struct ValidateResp<'a> {
    diagnostics: AllDiagnostics<'a>,
    statements: StatementsView<'a>,
    lineage: Option<LineageView<'a>>,
}

fn handle_analyze<W: Write>(
    dialect: &AnyDialect,
    analyzer: &mut Analyzer,
    req: &Value,
    writer: &mut W,
) -> Result<(), String> {
    let req: ValidateReq =
        serde_json::from_value(req.clone()).map_err(|e| format!("validate: {e}"))?;

    let mut catalog = if let Some(ddl) = req.schema_ddl.as_deref() {
        let (cat, errs) = Catalog::from_ddl(dialect.clone(), &[ddl]);
        if !errs.is_empty() {
            return Err(format!("schema_ddl: {}", errs.join("; ")));
        }
        cat
    } else {
        Catalog::new(dialect.clone())
    };
    if let Some(tables) = req.tables.as_deref() {
        let layer = catalog.layer_mut(CatalogLayer::Database);
        for t in tables {
            layer.insert_table(t.name.clone(), t.columns.clone(), false);
        }
    }
    if let Some(views) = req.views.as_deref() {
        let layer = catalog.layer_mut(CatalogLayer::Database);
        for v in views {
            layer.insert_view(v.name.clone(), v.columns.clone());
        }
    }

    let config = AnalysisConfig::default();
    let resolver = build_module_resolver(&req);
    let mut ctx = AnalysisContext::new(&mut catalog).with_config(config);
    if let Some(r) = resolver.as_deref() {
        ctx = ctx.with_resolver(r);
    }
    let model = analyzer.analyze(&req.sql, &mut ctx);

    match req.output.as_deref().unwrap_or("structured") {
        "structured" => {} // fall through to the structured path below.
        "text" => {
            let opts = req.render_options.unwrap_or_default();
            let r = DiagnosticRenderer::new(&req.sql, &opts.source_name);
            let mut buf: Vec<u8> = Vec::new();
            for d in model.diagnostics() {
                r.render_diagnostic(d, &mut buf)
                    .map_err(|e| format!("render: {e}"))?;
            }
            // `from_utf8` reuses the buffer (no extra allocation); the
            // renderer only writes UTF-8 so this can't fail in practice.
            let text = String::from_utf8(buf).map_err(|e| format!("utf-8: {e}"))?;
            return write_ok(writer, &RenderedResp { rendered: text });
        }
        other => return Err(format!("unknown output format: {other:?}")),
    }

    // `Analysis.lineage` exposes the lineage of the final
    // query-bearing statement (matches the pre-CLI-RPC Python API).
    let top_lineage = model.statements().iter().rev().find_map(lineage_view);

    let resp = ValidateResp {
        diagnostics: AllDiagnostics { model: &model },
        statements: StatementsView { model: &model },
        lineage: top_lineage,
    };
    write_ok(writer, &resp)
}

// ── validate: borrowed views ─────────────────────────────────────────────

struct AllDiagnostics<'a> {
    model: &'a syntaqlite::analysis::Analysis,
}

impl Serialize for AllDiagnostics<'_> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut seq = serializer.serialize_seq(Some(self.model.diagnostic_count()))?;
        for d in self.model.diagnostics() {
            seq.serialize_element(&DiagView::from(d))?;
        }
        seq.end()
    }
}

struct StatementsView<'a> {
    model: &'a syntaqlite::analysis::Analysis,
}

impl Serialize for StatementsView<'_> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let stmts = self.model.statements();
        let mut seq = serializer.serialize_seq(Some(stmts.len()))?;
        for s in stmts {
            seq.serialize_element(&StatementView { inner: s })?;
        }
        seq.end()
    }
}

struct StatementView<'a> {
    inner: &'a StatementAnalysis,
}

impl Serialize for StatementView<'_> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        let s = self.inner;
        let mut m = serializer.serialize_map(Some(4))?;
        m.serialize_entry("source", s.source())?;
        m.serialize_entry("diagnostics", &DiagsOfStatement(s))?;
        m.serialize_entry("defined_relations", &DefinedRelationsView(s))?;
        match lineage_view(s) {
            Some(l) => m.serialize_entry("lineage", &l)?,
            None => m.serialize_entry("lineage", &Value::Null)?,
        }
        m.end()
    }
}

struct DiagsOfStatement<'a>(&'a StatementAnalysis);

impl Serialize for DiagsOfStatement<'_> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let diags = self.0.diagnostics();
        let mut seq = serializer.serialize_seq(Some(diags.len()))?;
        for d in diags {
            seq.serialize_element(&DiagView::from(d))?;
        }
        seq.end()
    }
}

struct DefinedRelationsView<'a>(&'a StatementAnalysis);

impl Serialize for DefinedRelationsView<'_> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let rels = self.0.defined_relations();
        let mut seq = serializer.serialize_seq(Some(rels.len()))?;
        for d in rels {
            seq.serialize_element(&DefinedRelationRec {
                name: &d.name,
                is_view: d.is_view,
            })?;
        }
        seq.end()
    }
}

#[derive(Serialize)]
struct DefinedRelationRec<'a> {
    name: &'a str,
    is_view: bool,
}

// ── validate: diagnostic view ────────────────────────────────────────────

struct DiagView<'a> {
    inner: &'a Diagnostic,
}

impl<'a> From<&'a Diagnostic> for DiagView<'a> {
    fn from(inner: &'a Diagnostic) -> Self {
        Self { inner }
    }
}

impl Serialize for DiagView<'_> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        let d = self.inner;
        let help = d.help().map(|h| match h {
            Help::Suggestion(s) => s.as_str(),
        });
        let len = if help.is_some() { 6 } else { 5 };
        let mut m = serializer.serialize_map(Some(len))?;
        m.serialize_entry(
            "severity",
            match d.severity() {
                SemSeverity::Error => "error",
                SemSeverity::Warning => "warning",
                SemSeverity::Info => "info",
                SemSeverity::Hint => "hint",
            },
        )?;
        m.serialize_entry("message", &d.message().to_string())?;
        m.serialize_entry("start_offset", &d.start().as_usize())?;
        m.serialize_entry("end_offset", &d.end().as_usize())?;
        m.serialize_entry("code", &diag_code(d.message()))?;
        if let Some(h) = help {
            m.serialize_entry("help", h)?;
        }
        m.end()
    }
}

// ── validate: lineage view ───────────────────────────────────────────────

struct LineageView<'a> {
    stmt: &'a StatementAnalysis,
}

fn lineage_view(s: &StatementAnalysis) -> Option<LineageView<'_>> {
    // `lineage()` returns None for non-query statements; bail out so the
    // JSON says `null` rather than an empty lineage record.
    s.lineage()?;
    Some(LineageView { stmt: s })
}

impl Serialize for LineageView<'_> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        let s = self.stmt;
        let cols = s.lineage().expect("guarded by lineage_view");
        let rels = s
            .relations_accessed()
            .expect("relations_accessed present when lineage is present");
        let tables = s
            .physical_tables_accessed()
            .expect("physical_tables_accessed present when lineage is present");

        let mut m = serializer.serialize_map(Some(5))?;
        m.serialize_entry("complete", &cols.is_complete())?;
        m.serialize_entry("columns", &ColumnsSeq(cols.into_inner()))?;
        m.serialize_entry("relations", &RelationsSeq(rels.into_inner()))?;
        m.serialize_entry("physical_tables", &PhysicalTablesSeq(tables.into_inner()))?;
        m.serialize_entry(
            "unexpanded_views",
            &UnexpandedViewsSeq(s.unexpanded_views()),
        )?;
        m.end()
    }
}

struct ColumnsSeq<'a>(&'a [syntaqlite::analysis::ColumnLineage]);

impl Serialize for ColumnsSeq<'_> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
        for c in self.0 {
            let origin = c.origin.as_ref().map(|o| OriginRec {
                table: &o.table,
                column: &o.column,
            });
            seq.serialize_element(&ColumnRec {
                name: &c.name,
                index: c.index,
                origin,
            })?;
        }
        seq.end()
    }
}

#[derive(Serialize)]
struct ColumnRec<'a> {
    name: &'a str,
    index: u32,
    origin: Option<OriginRec<'a>>,
}

#[derive(Serialize)]
struct OriginRec<'a> {
    table: &'a str,
    column: &'a str,
}

struct RelationsSeq<'a>(&'a [syntaqlite::analysis::RelationAccess]);

impl Serialize for RelationsSeq<'_> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
        for r in self.0 {
            seq.serialize_element(&RelationRec {
                name: &r.name,
                kind: match r.kind {
                    RelationKind::Table => "table",
                    RelationKind::View => "view",
                },
            })?;
        }
        seq.end()
    }
}

#[derive(Serialize)]
struct RelationRec<'a> {
    name: &'a str,
    kind: &'static str,
}

struct PhysicalTablesSeq<'a>(&'a [syntaqlite::analysis::PhysicalTableAccess]);

impl Serialize for PhysicalTablesSeq<'_> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
        for t in self.0 {
            seq.serialize_element(t.name.as_str())?;
        }
        seq.end()
    }
}

struct UnexpandedViewsSeq<'a>(&'a [String]);

impl Serialize for UnexpandedViewsSeq<'_> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
        for v in self.0 {
            seq.serialize_element(v.as_str())?;
        }
        seq.end()
    }
}

// Keep in sync with `syntaqlite/src/semantic/ffi/codes.rs` — Python maps
// these back via `DiagnosticCode(d["code"])`.
const DIAG_CODE_PARSE_ERROR: u32 = 0;
const DIAG_CODE_UNKNOWN_TABLE: u32 = 1;
const DIAG_CODE_UNKNOWN_COLUMN: u32 = 2;
const DIAG_CODE_UNKNOWN_FUNCTION: u32 = 3;
const DIAG_CODE_UNKNOWN_MODULE: u32 = 4;
const DIAG_CODE_FUNCTION_ARITY: u32 = 5;
const DIAG_CODE_CTE_COLUMN_COUNT_MISMATCH: u32 = 6;

fn diag_code(msg: &DiagnosticMessage) -> u32 {
    match msg {
        DiagnosticMessage::ParseError(_) => DIAG_CODE_PARSE_ERROR,
        DiagnosticMessage::UnknownTable { .. } => DIAG_CODE_UNKNOWN_TABLE,
        DiagnosticMessage::UnknownColumn { .. } => DIAG_CODE_UNKNOWN_COLUMN,
        DiagnosticMessage::UnknownFunction { .. } => DIAG_CODE_UNKNOWN_FUNCTION,
        DiagnosticMessage::UnknownModule { .. } => DIAG_CODE_UNKNOWN_MODULE,
        DiagnosticMessage::FunctionArity { .. } => DIAG_CODE_FUNCTION_ARITY,
        DiagnosticMessage::CteColumnCountMismatch { .. } => DIAG_CODE_CTE_COLUMN_COUNT_MISMATCH,
    }
}