squonk 1.0.0

Extensible, fast, multi-dialect SQL tokenizer and parser for Rust
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
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Moderately AI Inc.

//! Transaction-control statement grammar (operational family).
//!
//! Owns `BEGIN` / `START TRANSACTION`, `COMMIT`, `ROLLBACK` (with the optional
//! savepoint rewind), `SAVEPOINT`, `RELEASE SAVEPOINT`, and `SET TRANSACTION`
//! characteristics, plus the leading-token recognizer the statement dispatcher in
//! [`super::query`] consults. As in the DDL/DML families, this vocabulary is matched
//! as contextual words rather than by keyword tag — the full ANSI/PostgreSQL
//! keyword inventory is a separate ticket, and none of these words are reserved.
//! The forms are accepted dialect-agnostically (no `FeatureSet` gate), with one
//! exception: SQLite's `BEGIN {DEFERRED | IMMEDIATE | EXCLUSIVE}` transaction-mode
//! modifier is gated by `utility_syntax.begin_transaction_mode` (PostgreSQL's `BEGIN`
//! takes its own, differently-shaped modifier vocabulary — the existing
//! [`TransactionMode`] list — so the two surfaces do not collide).

use crate::ast::{
    Expr, IsolationLevel, Literal, Span, Statement, TransactionAccessMode, TransactionBlockKeyword,
    TransactionMode, TransactionModeKind, TransactionStart, TransactionStatement, XaAssociation,
    XaStartKeyword, XaStatement, XaSuspend, Xid, split_radix_prefix,
};
use crate::error::ParseResult;
use crate::tokenizer::{Punctuation, TokenKind};
use thin_vec::ThinVec;

use super::Dialect;
use super::engine::Parser;
use super::expr::number_literal_kind;

impl<'a, D: Dialect> Parser<'a, D> {
    /// True if the current token begins a transaction-control statement.
    ///
    /// `SET` is shared with the session [`SET`](super::Parser::parse_session_statement);
    /// only `SET TRANSACTION` is transaction control, so it is claimed here only
    /// when `TRANSACTION` follows. The dispatcher must therefore test this before
    /// the session recognizer.
    pub(super) fn peek_starts_transaction_statement(&mut self) -> ParseResult<bool> {
        Ok(self.peek_is_contextual_keyword("BEGIN")?
            || self.peek_is_contextual_keyword("START")?
            || self.peek_is_contextual_keyword("COMMIT")?
            || self.peek_is_contextual_keyword("ROLLBACK")?
            || self.peek_is_contextual_keyword("SAVEPOINT")?
            || self.peek_is_contextual_keyword("RELEASE")?
            || (self.peek_is_contextual_keyword("SET")?
                && self.peek_nth_is_contextual_keyword(1, "TRANSACTION")?))
    }

    /// Parse a transaction-control statement into [`Statement::Transaction`].
    pub(super) fn parse_transaction_statement(&mut self) -> ParseResult<Statement<D::Ext>> {
        let start = self.current_span()?;
        let transaction = self.parse_transaction_statement_kind(start)?;
        let span = start.union(self.preceding_span());
        let meta = self.make_meta(span);
        Ok(Statement::Transaction {
            transaction: Box::new(transaction),
            meta,
        })
    }

    fn parse_transaction_statement_kind(
        &mut self,
        start: Span,
    ) -> ParseResult<TransactionStatement> {
        if self.eat_contextual_keyword("BEGIN")? {
            let mode = self.parse_transaction_mode_kind()?;
            let block = self.eat_transaction_block_keyword()?;
            let modes = self.parse_transaction_modes()?;
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(TransactionStatement::Begin {
                syntax: TransactionStart::Begin,
                mode,
                block,
                modes,
                meta,
            })
        } else if self.eat_contextual_keyword("START")? {
            self.expect_contextual_keyword("TRANSACTION")?;
            let modes = self.parse_transaction_modes()?;
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(TransactionStatement::Begin {
                syntax: TransactionStart::Start,
                mode: None,
                // The mandatory `TRANSACTION` is part of the `START TRANSACTION`
                // keyword, not an optional block noise word.
                block: None,
                modes,
                meta,
            })
        } else if self.eat_contextual_keyword("COMMIT")? {
            let block = self.eat_transaction_block_keyword()?;
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(TransactionStatement::Commit { block, meta })
        } else if self.eat_contextual_keyword("ROLLBACK")? {
            let block = self.eat_transaction_block_keyword()?;
            let (savepoint_keyword, to_savepoint) = if self.eat_contextual_keyword("TO")? {
                // The `SAVEPOINT` keyword is optional in `ROLLBACK TO [SAVEPOINT] <name>`.
                let savepoint_keyword = self.eat_contextual_keyword("SAVEPOINT")?;
                (savepoint_keyword, Some(self.parse_ident()?))
            } else {
                (false, None)
            };
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(TransactionStatement::Rollback {
                block,
                savepoint_keyword,
                to_savepoint,
                meta,
            })
        } else if self.eat_contextual_keyword("SAVEPOINT")? {
            let name = self.parse_ident()?;
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(TransactionStatement::Savepoint { name, meta })
        } else if self.eat_contextual_keyword("RELEASE")? {
            // The `SAVEPOINT` keyword is optional in `RELEASE [SAVEPOINT] <name>`.
            let savepoint_keyword = self.eat_contextual_keyword("SAVEPOINT")?;
            let savepoint = self.parse_ident()?;
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(TransactionStatement::Release {
                savepoint_keyword,
                savepoint,
                meta,
            })
        } else if self.eat_contextual_keyword("SET")? {
            self.expect_contextual_keyword("TRANSACTION")?;
            let modes = self.parse_transaction_modes()?;
            if modes.is_empty() {
                return Err(self.unexpected("a transaction mode after `SET TRANSACTION`"));
            }
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(TransactionStatement::SetCharacteristics { modes, meta })
        } else {
            Err(self.unexpected("a transaction-control statement"))
        }
    }

    /// Consume the interchangeable `WORK` / `TRANSACTION` block noise word that may
    /// follow `BEGIN`/`COMMIT`/`ROLLBACK`, returning which was written (or `None`).
    /// The two spellings carry no meaning; the tag lets a source-fidelity render
    /// replay the exact word.
    fn eat_transaction_block_keyword(&mut self) -> ParseResult<Option<TransactionBlockKeyword>> {
        if self.eat_contextual_keyword("WORK")? {
            Ok(Some(TransactionBlockKeyword::Work))
        } else if self.eat_contextual_keyword("TRANSACTION")? {
            Ok(Some(TransactionBlockKeyword::Transaction))
        } else {
            Ok(None)
        }
    }

    /// Parse SQLite's optional `{DEFERRED | IMMEDIATE | EXCLUSIVE}` transaction-mode
    /// modifier immediately after `BEGIN`, gated by `utility_syntax.begin_transaction_mode`.
    /// `None` when the dialect does not admit the modifier or the statement omits it; in
    /// either case the word (if any) is left unconsumed for the noise-word/mode-list parse
    /// that follows, so an unrecognized modifier surfaces as the existing trailing-token
    /// error rather than a bespoke one.
    fn parse_transaction_mode_kind(&mut self) -> ParseResult<Option<TransactionModeKind>> {
        if !self.features().utility_syntax.begin_transaction_mode {
            return Ok(None);
        }
        if self.eat_contextual_keyword("DEFERRED")? {
            Ok(Some(TransactionModeKind::Deferred))
        } else if self.eat_contextual_keyword("IMMEDIATE")? {
            Ok(Some(TransactionModeKind::Immediate))
        } else if self.eat_contextual_keyword("EXCLUSIVE")? {
            Ok(Some(TransactionModeKind::Exclusive))
        } else {
            Ok(None)
        }
    }

    /// Parse a possibly-empty transaction mode list (`START`/`BEGIN`,
    /// `SET TRANSACTION`, and the session `SET SESSION CHARACTERISTICS`).
    pub(super) fn parse_transaction_modes(&mut self) -> ParseResult<ThinVec<TransactionMode>> {
        let mut modes = ThinVec::new();
        while let Some(mode) = self.parse_optional_transaction_mode()? {
            modes.push(mode);
            // The mode separator is an optional comma: ANSI writes commas between
            // modes while PostgreSQL also allows bare juxtaposition. Consume one if
            // present; the loop ends when no further mode follows.
            let _ = self.eat_punct(Punctuation::Comma)?;
        }
        Ok(modes)
    }

    fn parse_optional_transaction_mode(&mut self) -> ParseResult<Option<TransactionMode>> {
        let start = self.current_span()?;
        if self.eat_contextual_keyword("ISOLATION")? {
            self.expect_contextual_keyword("LEVEL")?;
            let level = self.parse_isolation_level()?;
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(Some(TransactionMode::IsolationLevel { level, meta }))
        } else if self.eat_contextual_keyword("READ")? {
            let access = if self.eat_contextual_keyword("ONLY")? {
                TransactionAccessMode::ReadOnly
            } else if self.eat_contextual_keyword("WRITE")? {
                TransactionAccessMode::ReadWrite
            } else {
                return Err(self.unexpected("`ONLY` or `WRITE` after `READ`"));
            };
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(Some(TransactionMode::AccessMode { access, meta }))
        } else if self.eat_contextual_keyword("DEFERRABLE")? {
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(Some(TransactionMode::Deferrable {
                deferrable: true,
                meta,
            }))
        } else if self.eat_contextual_keyword("NOT")? {
            // `NOT` opens only `NOT DEFERRABLE` in a transaction mode list.
            self.expect_contextual_keyword("DEFERRABLE")?;
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(Some(TransactionMode::Deferrable {
                deferrable: false,
                meta,
            }))
        } else {
            Ok(None)
        }
    }

    fn parse_isolation_level(&mut self) -> ParseResult<IsolationLevel> {
        if self.eat_contextual_keyword("READ")? {
            if self.eat_contextual_keyword("UNCOMMITTED")? {
                Ok(IsolationLevel::ReadUncommitted)
            } else if self.eat_contextual_keyword("COMMITTED")? {
                Ok(IsolationLevel::ReadCommitted)
            } else {
                Err(self.unexpected("`UNCOMMITTED` or `COMMITTED` after `READ`"))
            }
        } else if self.eat_contextual_keyword("REPEATABLE")? {
            self.expect_contextual_keyword("READ")?;
            Ok(IsolationLevel::RepeatableRead)
        } else if self.eat_contextual_keyword("SERIALIZABLE")? {
            Ok(IsolationLevel::Serializable)
        } else {
            Err(self.unexpected("an isolation level"))
        }
    }

    /// Parse a MySQL `XA` distributed-transaction statement into [`Statement::Xa`],
    /// reached under [`UtilitySyntax::xa_transactions`](crate::ast::dialect::UtilitySyntax).
    pub(super) fn parse_xa_statement(&mut self) -> ParseResult<Statement<D::Ext>> {
        let start = self.current_span()?;
        self.expect_contextual_keyword("XA")?;
        let xa = self.parse_xa_statement_kind(start)?;
        let span = start.union(self.preceding_span());
        let meta = self.make_meta(span);
        Ok(Statement::Xa {
            xa: Box::new(xa),
            meta,
        })
    }

    fn parse_xa_statement_kind(&mut self, start: Span) -> ParseResult<XaStatement> {
        // `begin_or_start`: `START` and `BEGIN` are exact synonyms for the branch-start verb.
        let keyword = if self.eat_contextual_keyword("START")? {
            Some(XaStartKeyword::Start)
        } else if self.eat_contextual_keyword("BEGIN")? {
            Some(XaStartKeyword::Begin)
        } else {
            None
        };
        if let Some(keyword) = keyword {
            let xid = self.parse_xid()?;
            // `opt_join_or_resume`: valid only on the branch-start verb.
            let association = if self.eat_contextual_keyword("JOIN")? {
                Some(XaAssociation::Join)
            } else if self.eat_contextual_keyword("RESUME")? {
                Some(XaAssociation::Resume)
            } else {
                None
            };
            let meta = self.make_meta(start.union(self.preceding_span()));
            return Ok(XaStatement::Start {
                keyword,
                xid,
                association,
                meta,
            });
        }
        if self.eat_contextual_keyword("END")? {
            let xid = self.parse_xid()?;
            // `opt_suspend`: `SUSPEND`, optionally `SUSPEND FOR MIGRATE`.
            let suspend = if self.eat_contextual_keyword("SUSPEND")? {
                if self.eat_contextual_keyword("FOR")? {
                    self.expect_contextual_keyword("MIGRATE")?;
                    Some(XaSuspend::SuspendForMigrate)
                } else {
                    Some(XaSuspend::Suspend)
                }
            } else {
                None
            };
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(XaStatement::End { xid, suspend, meta })
        } else if self.eat_contextual_keyword("PREPARE")? {
            let xid = self.parse_xid()?;
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(XaStatement::Prepare { xid, meta })
        } else if self.eat_contextual_keyword("COMMIT")? {
            let xid = self.parse_xid()?;
            // `opt_one_phase`: the `ONE PHASE` single-phase-commit optimisation.
            let one_phase = if self.eat_contextual_keyword("ONE")? {
                self.expect_contextual_keyword("PHASE")?;
                true
            } else {
                false
            };
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(XaStatement::Commit {
                xid,
                one_phase,
                meta,
            })
        } else if self.eat_contextual_keyword("ROLLBACK")? {
            let xid = self.parse_xid()?;
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(XaStatement::Rollback { xid, meta })
        } else if self.eat_contextual_keyword("RECOVER")? {
            // `opt_convert_xid`: both words are mandatory together.
            let convert_xid = if self.eat_contextual_keyword("CONVERT")? {
                self.expect_contextual_keyword("XID")?;
                true
            } else {
                false
            };
            let meta = self.make_meta(start.union(self.preceding_span()));
            Ok(XaStatement::Recover { convert_xid, meta })
        } else {
            Err(self.unexpected(
                "an XA verb (`START`/`BEGIN`/`END`/`PREPARE`/`COMMIT`/`ROLLBACK`/`RECOVER`)",
            ))
        }
    }

    /// Parse an XA transaction-branch identifier `gtrid [, bqual [, formatID]]`
    /// (`sql_yacc.yy` `xid`). `formatID` is admitted only after a `bqual`.
    fn parse_xid(&mut self) -> ParseResult<Xid> {
        let gtrid = self.parse_xid_text("an XID `gtrid` string or hex/binary literal")?;
        let start = gtrid.meta.span;
        let (bqual, format_id) = if self.eat_punct(Punctuation::Comma)? {
            let bqual =
                self.parse_xid_text("an XID `bqual` string or hex/binary literal after `,`")?;
            let format_id = if self.eat_punct(Punctuation::Comma)? {
                Some(self.parse_xid_format_id()?)
            } else {
                None
            };
            (Some(bqual), format_id)
        } else {
            (None, None)
        };
        let meta = self.make_meta(start.union(self.preceding_span()));
        Ok(Xid {
            gtrid,
            bqual,
            format_id,
            meta,
        })
    }

    /// Parse an xid `gtrid`/`bqual` byte-string constant (`text_string`): a character-string
    /// literal, or a hexadecimal / binary literal (`0x…` / `X'…'` / `0b…` / `B'…'`). A bare
    /// decimal number is *not* accepted here (only `HEX_NUM` / `BIN_NUM`), matching the engine.
    fn parse_xid_text(&mut self, expected: &'static str) -> ParseResult<Literal> {
        let Some(token) = self.peek()? else {
            return Err(self.unexpected(expected));
        };
        match token.kind {
            // The string forms (`'…'`, `X'…'`, `B'…'`) reuse the expression string-literal
            // reader, so the bit-string kind and any adjacent-literal continuation resolve
            // exactly as elsewhere; it always yields an `Expr::Literal`.
            TokenKind::String => match self.parse_string_literal(token)? {
                Expr::Literal { literal, .. } => Ok(literal),
                other => unreachable!("parse_string_literal yields Expr::Literal, got {other:?}"),
            },
            // A radix-prefixed number (`0x…` / `0b…`) is the `HEX_NUM` / `BIN_NUM` spelling of a
            // byte string; a base-10 number is a plain integer, which `text_string` rejects.
            TokenKind::Number if split_radix_prefix(self.span_text(token.span)).0 != 10 => {
                self.advance()?;
                Ok(Literal {
                    kind: number_literal_kind(
                        self.span_text(token.span),
                        self.parse_float_as_decimal(),
                    ),
                    meta: self.make_meta(token.span),
                })
            }
            _ => Err(self.unexpected(expected)),
        }
    }

    /// Parse an xid `formatID` (`ulong_num`): any non-negative numeric literal. A leading
    /// sign is a separate token, so `-1` is left for the trailing-token check and rejects, as
    /// the engine does.
    fn parse_xid_format_id(&mut self) -> ParseResult<Literal> {
        let expected = "a numeric `formatID` after the branch qualifier";
        let Some(token) = self.peek()? else {
            return Err(self.unexpected(expected));
        };
        if token.kind != TokenKind::Number {
            return Err(self.unexpected(expected));
        }
        self.advance()?;
        Ok(Literal {
            kind: number_literal_kind(self.span_text(token.span), self.parse_float_as_decimal()),
            meta: self.make_meta(token.span),
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::ast::{
        IsolationLevel, Resolver as _, Span, Spanned, Statement, TransactionAccessMode,
        TransactionMode, TransactionStart, TransactionStatement,
    };
    use crate::parser::{TestDialect, parse_with};

    fn parse_transaction(sql: &str) -> TransactionStatement {
        let parsed = parse_with(sql, TestDialect).unwrap_or_else(|err| panic!("{sql:?}: {err:?}"));
        let [Statement::Transaction { transaction, .. }] = parsed.statements() else {
            panic!(
                "{sql:?} did not parse to one transaction statement: {:?}",
                parsed.statements(),
            );
        };
        (**transaction).clone()
    }

    /// The dispatch contract: each leading keyword the transaction family claims
    /// is routed by the central `parse_statement` to this module's entry and yields a
    /// `Statement::Transaction`. This pins the dispatch boundary — the full claimed
    /// keyword set — independently of the per-construct grammar the other tests cover;
    /// `parse_transaction` panics if a keyword fails to route to this family.
    #[test]
    fn dispatch_routes_transaction_keywords_to_this_family() {
        for sql in [
            "BEGIN",
            "START TRANSACTION",
            "COMMIT",
            "ROLLBACK",
            "SAVEPOINT sp",
            "RELEASE sp",
            "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE",
        ] {
            let _ = parse_transaction(sql);
        }
    }

    #[test]
    fn begin_and_start_transaction_share_a_shape_with_a_surface_tag() {
        // BEGIN and START TRANSACTION are synonyms recorded by a surface tag, and
        // the WORK/TRANSACTION noise words are accepted but not represented.
        for (sql, expected) in [
            ("BEGIN", TransactionStart::Begin),
            ("BEGIN WORK", TransactionStart::Begin),
            ("BEGIN TRANSACTION", TransactionStart::Begin),
            ("START TRANSACTION", TransactionStart::Start),
        ] {
            let TransactionStatement::Begin { syntax, modes, .. } = parse_transaction(sql) else {
                panic!("{sql:?} should be a Begin statement");
            };
            assert_eq!(syntax, expected, "{sql:?}");
            assert!(modes.is_empty(), "{sql:?} has no modes");
        }
    }

    #[test]
    fn begin_statement_span_covers_the_whole_construct() {
        let parsed = parse_with("START TRANSACTION", TestDialect).expect("parses");
        let [stmt @ Statement::Transaction { .. }] = parsed.statements() else {
            panic!("expected one transaction statement");
        };
        assert_eq!(stmt.span(), Span::new(0, "START TRANSACTION".len() as u32));
    }

    #[test]
    fn transaction_modes_parse_with_or_without_commas() {
        // ANSI comma-separated and PostgreSQL space-separated mode lists are both
        // accepted and yield the same shape.
        for sql in [
            "START TRANSACTION ISOLATION LEVEL SERIALIZABLE, READ ONLY",
            "START TRANSACTION ISOLATION LEVEL SERIALIZABLE READ ONLY",
        ] {
            let TransactionStatement::Begin { modes, .. } = parse_transaction(sql) else {
                panic!("{sql:?} should be a Begin statement");
            };
            assert!(
                matches!(
                    modes.as_slice(),
                    [
                        TransactionMode::IsolationLevel {
                            level: IsolationLevel::Serializable,
                            ..
                        },
                        TransactionMode::AccessMode {
                            access: TransactionAccessMode::ReadOnly,
                            ..
                        },
                    ],
                ),
                "{sql:?} modes: {modes:?}",
            );
        }
    }

    #[test]
    fn all_isolation_levels_parse() {
        for (sql, expected) in [
            (
                "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED",
                IsolationLevel::ReadUncommitted,
            ),
            (
                "SET TRANSACTION ISOLATION LEVEL READ COMMITTED",
                IsolationLevel::ReadCommitted,
            ),
            (
                "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ",
                IsolationLevel::RepeatableRead,
            ),
            (
                "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE",
                IsolationLevel::Serializable,
            ),
        ] {
            let TransactionStatement::SetCharacteristics { modes, .. } = parse_transaction(sql)
            else {
                panic!("{sql:?} should be SET TRANSACTION");
            };
            assert!(
                matches!(
                    modes.as_slice(),
                    [TransactionMode::IsolationLevel { level, .. }] if *level == expected,
                ),
                "{sql:?} modes: {modes:?}",
            );
        }
    }

    #[test]
    fn deferrable_mode_parses_on_start_and_set_transaction() {
        for (sql, expected) in [
            ("START TRANSACTION DEFERRABLE", true),
            ("START TRANSACTION NOT DEFERRABLE", false),
        ] {
            let TransactionStatement::Begin { modes, .. } = parse_transaction(sql) else {
                panic!("{sql:?} should be a Begin statement");
            };
            assert!(
                matches!(
                    modes.as_slice(),
                    [TransactionMode::Deferrable { deferrable, .. }] if *deferrable == expected,
                ),
                "{sql:?} modes: {modes:?}",
            );
        }
        // The mode rides `SET TRANSACTION` and mixes with the others.
        let TransactionStatement::SetCharacteristics { modes, .. } =
            parse_transaction("SET TRANSACTION READ ONLY, NOT DEFERRABLE")
        else {
            panic!("expected SET TRANSACTION");
        };
        assert!(matches!(
            modes.as_slice(),
            [
                TransactionMode::AccessMode { .. },
                TransactionMode::Deferrable {
                    deferrable: false,
                    ..
                },
            ],
        ));
    }

    #[test]
    fn commit_and_rollback_parse_with_optional_savepoint_rewind() {
        assert!(matches!(
            parse_transaction("COMMIT"),
            TransactionStatement::Commit { .. }
        ));
        assert!(matches!(
            parse_transaction("COMMIT WORK"),
            TransactionStatement::Commit { .. }
        ));
        assert!(matches!(
            parse_transaction("ROLLBACK"),
            TransactionStatement::Rollback {
                to_savepoint: None,
                ..
            }
        ));
        // `TO SAVEPOINT name` and the SAVEPOINT-less `TO name` are the same shape.
        for sql in ["ROLLBACK TO SAVEPOINT sp1", "ROLLBACK TO sp1"] {
            assert!(
                matches!(
                    parse_transaction(sql),
                    TransactionStatement::Rollback {
                        to_savepoint: Some(_),
                        ..
                    }
                ),
                "{sql:?}",
            );
        }
    }

    #[test]
    fn savepoint_and_release_capture_the_name() {
        let parsed = parse_with("SAVEPOINT sp1", TestDialect).expect("parses");
        let [Statement::Transaction { transaction, .. }] = parsed.statements() else {
            panic!("expected a transaction statement");
        };
        let TransactionStatement::Savepoint { name, .. } = &**transaction else {
            panic!("expected SAVEPOINT");
        };
        assert_eq!(parsed.resolver().resolve(name.sym), "sp1");

        for sql in ["RELEASE SAVEPOINT sp1", "RELEASE sp1"] {
            assert!(
                matches!(parse_transaction(sql), TransactionStatement::Release { .. }),
                "{sql:?}",
            );
        }
    }

    #[test]
    fn malformed_transaction_statements_are_rejected() {
        for sql in [
            "SAVEPOINT",                 // missing name
            "RELEASE",                   // missing name
            "START",                     // missing TRANSACTION
            "SET TRANSACTION",           // missing mode
            "START TRANSACTION READ",    // READ without ONLY/WRITE
            "SET TRANSACTION ISOLATION", // ISOLATION without LEVEL
            "START TRANSACTION NOT",     // NOT without DEFERRABLE
        ] {
            assert!(
                parse_with(sql, TestDialect).is_err(),
                "{sql:?} should be rejected",
            );
        }
    }

    // --- XA distributed-transaction family -----------------------------------

    use crate::ast::{XaAssociation, XaStartKeyword, XaStatement, XaSuspend};
    use crate::parser::FeatureDialect;
    use crate::render::Renderer;

    /// A MySQL-featured dialect so the `xa_transactions`-gated `XA` family parses and
    /// renders back to a MySQL target through one round-trip value.
    const XA_DIALECT: FeatureDialect = FeatureDialect {
        features: &crate::ast::dialect::FeatureSet::MYSQL,
    };

    fn parse_xa(sql: &str) -> XaStatement {
        let parsed = parse_with(sql, XA_DIALECT).unwrap_or_else(|err| panic!("{sql:?}: {err:?}"));
        let [Statement::Xa { xa, .. }] = parsed.statements() else {
            panic!(
                "{sql:?} did not parse to one XA statement: {:?}",
                parsed.statements(),
            );
        };
        (**xa).clone()
    }

    #[test]
    fn xa_dispatch_routes_only_under_the_gate() {
        // The leading `XA` keyword routes to this family only when `xa_transactions` is on;
        // it is not dispatched under ANSI, where it surfaces as an unknown statement.
        let _ = parse_xa("XA PREPARE 'x'");
        assert!(
            parse_with("XA PREPARE 'x'", TestDialect).is_err(),
            "`XA` must not be dispatched without the gate",
        );
    }

    #[test]
    fn xa_every_verb_parses_and_round_trips() {
        for (sql, check) in [
            (
                "XA START 'gtrid'",
                &(|xa: &XaStatement| {
                    matches!(
                        xa,
                        XaStatement::Start {
                            keyword: XaStartKeyword::Start,
                            association: None,
                            ..
                        }
                    )
                }) as &dyn Fn(&XaStatement) -> bool,
            ),
            ("XA BEGIN 'gtrid'", &|xa| {
                matches!(
                    xa,
                    XaStatement::Start {
                        keyword: XaStartKeyword::Begin,
                        ..
                    }
                )
            }),
            ("XA START 'gtrid' JOIN", &|xa| {
                matches!(
                    xa,
                    XaStatement::Start {
                        association: Some(XaAssociation::Join),
                        ..
                    }
                )
            }),
            ("XA START 'gtrid' RESUME", &|xa| {
                matches!(
                    xa,
                    XaStatement::Start {
                        association: Some(XaAssociation::Resume),
                        ..
                    }
                )
            }),
            ("XA END 'gtrid'", &|xa| {
                matches!(xa, XaStatement::End { suspend: None, .. })
            }),
            ("XA END 'gtrid' SUSPEND", &|xa| {
                matches!(
                    xa,
                    XaStatement::End {
                        suspend: Some(XaSuspend::Suspend),
                        ..
                    }
                )
            }),
            ("XA END 'gtrid' SUSPEND FOR MIGRATE", &|xa| {
                matches!(
                    xa,
                    XaStatement::End {
                        suspend: Some(XaSuspend::SuspendForMigrate),
                        ..
                    }
                )
            }),
            ("XA PREPARE 'gtrid'", &|xa| {
                matches!(xa, XaStatement::Prepare { .. })
            }),
            ("XA COMMIT 'gtrid'", &|xa| {
                matches!(
                    xa,
                    XaStatement::Commit {
                        one_phase: false,
                        ..
                    }
                )
            }),
            ("XA COMMIT 'gtrid' ONE PHASE", &|xa| {
                matches!(
                    xa,
                    XaStatement::Commit {
                        one_phase: true,
                        ..
                    }
                )
            }),
            ("XA ROLLBACK 'gtrid'", &|xa| {
                matches!(xa, XaStatement::Rollback { .. })
            }),
            ("XA RECOVER", &|xa| {
                matches!(
                    xa,
                    XaStatement::Recover {
                        convert_xid: false,
                        ..
                    }
                )
            }),
            ("XA RECOVER CONVERT XID", &|xa| {
                matches!(
                    xa,
                    XaStatement::Recover {
                        convert_xid: true,
                        ..
                    }
                )
            }),
        ] {
            let xa = parse_xa(sql);
            assert!(check(&xa), "{sql:?} shape: {xa:?}");
            let parsed = parse_with(sql, XA_DIALECT).expect("parses");
            let rendered = Renderer::new(XA_DIALECT)
                .render_parsed(&parsed)
                .unwrap_or_else(|err| panic!("{sql:?} renders: {err:?}"));
            assert_eq!(rendered, sql, "round-trip");
        }
    }

    #[test]
    fn xid_admits_string_hex_and_binary_forms_and_round_trips() {
        // `gtrid`/`bqual` are `text_string`: a character string, a `0x`/`X'…'` hex literal,
        // or a `0b`/`B'…'` binary literal; `formatID` is any non-negative numeric literal.
        // Each spelling round-trips byte-identically.
        for sql in [
            "XA START 'gtrid', 'bqual'",
            "XA START 'gtrid', 'bqual', 42",
            "XA START 0x1234",
            "XA START 0x1234, 0xABCD, 7",
            "XA START X'1234'",
            "XA START 0b1010",
            "XA START B'1010'",
            "XA START 'g', 'b', 0x10",
            "XA START 'g', 'b', 3.5",
        ] {
            let parsed =
                parse_with(sql, XA_DIALECT).unwrap_or_else(|err| panic!("{sql:?}: {err:?}"));
            assert!(
                matches!(parsed.statements(), [Statement::Xa { .. }]),
                "{sql:?} should parse to an XA statement",
            );
            let rendered = Renderer::new(XA_DIALECT)
                .render_parsed(&parsed)
                .unwrap_or_else(|err| panic!("{sql:?} renders: {err:?}"));
            assert_eq!(rendered, sql, "round-trip");
        }
    }

    #[test]
    fn xa_reject_boundaries_match_the_engine() {
        // Every arm here is a live-8.4.10 `ER_PARSE_ERROR` (1064): xid mandatory where the
        // grammar requires it, the suffix keywords bound to their own verbs, `formatID`
        // numeric and only after a `bqual`, and a bare decimal `gtrid` rejected.
        for sql in [
            "XA START",                      // missing xid
            "XA PREPARE",                    // missing xid
            "XA START 42",                   // decimal gtrid is not text_string
            "XA START 'g', 'b', 'c'",        // formatID must be numeric
            "XA START 'g' JOIN RESUME",      // at most one association keyword
            "XA START 'gtrid' SUSPEND",      // SUSPEND is an END-only suffix
            "XA END 'gtrid' JOIN",           // JOIN is a START-only suffix
            "XA END 'g' FOR MIGRATE",        // FOR MIGRATE requires SUSPEND
            "XA END 'g' SUSPEND MIGRATE",    // MIGRATE requires the FOR keyword
            "XA COMMIT 'gtrid' JOIN",        // COMMIT takes only ONE PHASE
            "XA COMMIT 'gtrid' TWO PHASE",   // only ONE PHASE
            "XA PREPARE 'gtrid' ONE PHASE",  // PREPARE takes no suffix
            "XA ROLLBACK 'gtrid' ONE PHASE", // ROLLBACK takes no suffix
            "XA RECOVER 'gtrid'",            // RECOVER takes no xid
            "XA RECOVER CONVERT",            // CONVERT requires XID
            "XA WOBBLE 'gtrid'",             // unknown verb
        ] {
            assert!(
                parse_with(sql, XA_DIALECT).is_err(),
                "{sql:?} should be rejected",
            );
        }
    }
}