Skip to main content

halephant_core/sql/
parser.rs

1//! Token-level statement parser.
2//!
3//! Given a slice of [`Token`]s from [`super::lexer::lex`], walk the
4//! leading tokens and build a [`Statement`] AST.
5//!
6//! This is deliberately a tiny hand-written recursive-descent walker
7//! rather than a second chumsky parser layer. Chumsky shines on
8//! complex grammars with backtracking and error recovery, neither of
9//! which apply here: the grammar is ~10 statement shapes, every
10//! unrecognised input falls through to `Statement::Other`, and there
11//! are no errors to surface. Imperative cursor-based parsing is
12//! clearer and produces less machinery for a reader to digest.
13
14use super::ast::{
15    DeallocateTarget, DiscardTarget, ResetTarget, SetScope, SetValue, Statement,
16    TransactionOptions, UnlistenTarget,
17};
18use super::lexer::{Token, lex};
19
20// ---------------------------------------------------------------------------
21// Public entry point
22// ---------------------------------------------------------------------------
23
24/// Parse a SQL string into a [`Statement`].
25///
26/// The parser inspects only the leading tokens of the query, so for
27/// multi-statement input it classifies by the first statement — the
28/// same convention every proxy-level parser uses.
29pub fn parse(sql: &str) -> Statement {
30    let tokens = lex(sql);
31    let mut cur = Cursor::new(&tokens);
32    parse_statement(&mut cur)
33}
34
35// ---------------------------------------------------------------------------
36// Cursor
37// ---------------------------------------------------------------------------
38
39/// Linear iterator over the token slice with enough lookahead for the
40/// shapes we care about (one-token for most branches, two-token for
41/// `SET SESSION CHARACTERISTICS`). Everything is `O(1)`: no cloning,
42/// no backtracking buffer.
43struct Cursor<'a> {
44    tokens: &'a [Token],
45    pos: usize,
46}
47
48impl<'a> Cursor<'a> {
49    fn new(tokens: &'a [Token]) -> Self {
50        Self { tokens, pos: 0 }
51    }
52
53    fn peek(&self) -> Option<&'a Token> {
54        self.tokens.get(self.pos)
55    }
56
57    /// Look at the token `offset` positions ahead without advancing.
58    /// `peek_at(0)` is equivalent to `peek()`.
59    fn peek_at(&self, offset: usize) -> Option<&'a Token> {
60        self.tokens.get(self.pos + offset)
61    }
62
63    fn advance(&mut self) -> Option<&'a Token> {
64        let t = self.tokens.get(self.pos)?;
65        self.pos += 1;
66        Some(t)
67    }
68
69    /// If the next token is a `Word(expected)`, consume it and return
70    /// `true`. Otherwise leave the cursor untouched.
71    fn eat_word(&mut self, expected: &str) -> bool {
72        if matches!(self.peek(), Some(Token::Word(w)) if w == expected) {
73            self.pos += 1;
74            return true;
75        }
76        false
77    }
78
79    /// Consume the next token as an identifier — either an unquoted
80    /// `Word` (lowercased by the lexer) or a `QuotedIdent` (case
81    /// preserved). Returns `None` on any other token.
82    fn eat_identifier(&mut self) -> Option<String> {
83        match self.peek()? {
84            Token::Word(name) | Token::QuotedIdent(name) => {
85                let s = name.clone();
86                self.pos += 1;
87                Some(s)
88            }
89            _ => None,
90        }
91    }
92}
93
94// ---------------------------------------------------------------------------
95// Statement dispatch
96// ---------------------------------------------------------------------------
97
98fn parse_statement(cur: &mut Cursor<'_>) -> Statement {
99    let Some(Token::Word(first)) = cur.peek() else {
100        return Statement::Other;
101    };
102    match first.as_str() {
103        "listen" => parse_listen(cur),
104        "unlisten" => parse_unlisten(cur),
105        "set" => parse_set(cur),
106        "reset" => parse_reset(cur),
107        "discard" => parse_discard(cur),
108        "deallocate" => parse_deallocate(cur),
109        "begin" | "start" => parse_begin(cur),
110        "commit" | "end" => Statement::Commit,
111        "rollback" | "abort" => Statement::Rollback,
112        "select" | "table" | "values" => Statement::Select,
113        "insert" => Statement::Insert,
114        "update" => Statement::Update,
115        "delete" | "truncate" => Statement::Delete,
116        "copy" => Statement::Copy,
117        "with" => parse_cte_wrapped(cur),
118        _ => Statement::Other,
119    }
120}
121
122// ---------------------------------------------------------------------------
123// LISTEN / UNLISTEN
124// ---------------------------------------------------------------------------
125
126fn parse_listen(cur: &mut Cursor<'_>) -> Statement {
127    cur.advance(); // LISTEN
128    match cur.eat_identifier() {
129        Some(channel) => Statement::Listen { channel },
130        // `LISTEN` without a following identifier is malformed SQL;
131        // collapse to Other rather than fabricate an empty channel.
132        None => Statement::Other,
133    }
134}
135
136fn parse_unlisten(cur: &mut Cursor<'_>) -> Statement {
137    cur.advance(); // UNLISTEN
138
139    // Note: the `Token::Star` arm is only reachable for an unquoted
140    // `*` in the source text. A double-quoted `"*"` comes in as
141    // `Token::QuotedIdent("*")` and falls into the identifier arm
142    // below, becoming `Channel("*")` — the right behaviour, since
143    // the quoted form is a literal identifier, not the wildcard.
144    match cur.peek() {
145        Some(Token::Star) => {
146            cur.advance();
147            Statement::Unlisten {
148                target: UnlistenTarget::Star,
149            }
150        }
151        Some(Token::Word(name) | Token::QuotedIdent(name)) => {
152            let name = name.clone();
153            cur.advance();
154            Statement::Unlisten {
155                target: UnlistenTarget::Channel(name),
156            }
157        }
158        _ => Statement::Other,
159    }
160}
161
162// ---------------------------------------------------------------------------
163// SET / RESET / DISCARD
164// ---------------------------------------------------------------------------
165
166fn parse_set(cur: &mut Cursor<'_>) -> Statement {
167    cur.advance(); // SET
168
169    // `SET TRANSACTION <modes>` — transaction characteristics for
170    // the current transaction. Must come before the LOCAL/SESSION
171    // check because it takes no scope prefix.
172    if cur.eat_word("transaction") {
173        return Statement::SetTransaction {
174            options: parse_transaction_options(cur),
175        };
176    }
177
178    // Scope prefix: LOCAL or SESSION. SESSION has the extra special
179    // case `SET SESSION CHARACTERISTICS AS TRANSACTION <modes>`, which
180    // sets session-level transaction defaults and is also a
181    // SetTransaction variant — because the grammar after `AS
182    // TRANSACTION` is the same.
183    let scope = if cur.eat_word("local") {
184        SetScope::Local
185    } else if cur.eat_word("session") {
186        if cur.eat_word("characteristics") {
187            if cur.eat_word("as") && cur.eat_word("transaction") {
188                return Statement::SetTransaction {
189                    options: parse_transaction_options(cur),
190                };
191            }
192            // `SET SESSION CHARACTERISTICS ...` without `AS
193            // TRANSACTION` is malformed.
194            return Statement::Other;
195        }
196        SetScope::Session
197    } else {
198        SetScope::Session
199    };
200
201    // `SET [scope] parameter (= | TO) value`
202    let Some(parameter) = cur.eat_identifier() else {
203        return Statement::Other;
204    };
205
206    // Consume the `=` (arrives as `Token::Other` from the lexer) or
207    // the `TO` keyword.
208    match cur.peek() {
209        Some(Token::Word(w)) if w == "to" => {
210            cur.advance();
211        }
212        Some(Token::Other) => {
213            cur.advance();
214        }
215        _ => return Statement::Other,
216    }
217
218    let value = match cur.peek() {
219        Some(Token::Word(w)) if w == "default" => {
220            cur.advance();
221            SetValue::Default
222        }
223        Some(Token::Word(v) | Token::Literal(v) | Token::Number(v)) => {
224            let v = v.clone();
225            cur.advance();
226            SetValue::Literal(v)
227        }
228        // Signed numeric values like `SET work_mem = -1` or
229        // `SET seed = +0.5`: the sign character lexes as
230        // `Token::Other` because the lexer collapses unknown
231        // punctuation uniformly. If the token immediately after the
232        // sign is a Number, consume both and record the parameter
233        // as dirty. The actual numeric value is irrelevant for
234        // `dirty_vars` tracking (which only keys on the parameter
235        // name), so we store the bare number without the sign.
236        //
237        // Known limitation: `SET default_transaction_read_only = -0`
238        // is pathological — PostgreSQL would treat it as
239        // `0`/read-write, but halephant's `is_read_write_override`
240        // check runs `as_boolean("0")` against the stored literal
241        // (sign stripped), so it would correctly flag this. For any
242        // other signed value, `as_boolean` on the bare digits
243        // returns `None`, so no false read-write override fires.
244        Some(Token::Other) if matches!(cur.peek_at(1), Some(Token::Number(_))) => {
245            cur.advance(); // sign
246            let Some(Token::Number(v)) = cur.peek() else {
247                unreachable!("peek_at(1) matched Token::Number above");
248            };
249            let v = v.clone();
250            cur.advance();
251            SetValue::Literal(v)
252        }
253        _ => return Statement::Other,
254    };
255
256    Statement::Set {
257        scope,
258        parameter,
259        value,
260    }
261}
262
263fn parse_reset(cur: &mut Cursor<'_>) -> Statement {
264    cur.advance(); // RESET
265    match cur.peek() {
266        Some(Token::Word(w)) if w == "all" => {
267            cur.advance();
268            Statement::Reset {
269                target: ResetTarget::All,
270            }
271        }
272        Some(Token::Word(_) | Token::QuotedIdent(_)) => {
273            // Unwrap is safe: we just matched Word/QuotedIdent above.
274            let name = cur.eat_identifier().expect("identifier after RESET");
275            Statement::Reset {
276                target: ResetTarget::Parameter(name),
277            }
278        }
279        _ => Statement::Other,
280    }
281}
282
283fn parse_discard(cur: &mut Cursor<'_>) -> Statement {
284    cur.advance(); // DISCARD
285    let Some(Token::Word(w)) = cur.peek() else {
286        // Bare `DISCARD` is not valid SQL — fall through so the
287        // server surfaces the syntax error.
288        return Statement::Other;
289    };
290    let target = match w.as_str() {
291        "all" => DiscardTarget::All,
292        "plans" => DiscardTarget::Plans,
293        "sequences" => DiscardTarget::Sequences,
294        "temporary" | "temp" => DiscardTarget::Temp,
295        // Unknown DISCARD subtarget — PostgreSQL would reject it too.
296        _ => return Statement::Other,
297    };
298    cur.advance();
299    Statement::Discard { target }
300}
301
302fn parse_deallocate(cur: &mut Cursor<'_>) -> Statement {
303    cur.advance(); // DEALLOCATE
304
305    // `PREPARE` is an optional noise keyword between DEALLOCATE and
306    // the target; consume it if present and keep going.
307    cur.eat_word("prepare");
308
309    match cur.peek() {
310        // `DEALLOCATE [PREPARE] ALL` — must be the unquoted `ALL`
311        // keyword, not a (case-preserved) quoted identifier named
312        // "ALL".
313        Some(Token::Word(w)) if w == "all" => {
314            cur.advance();
315            Statement::Deallocate {
316                target: DeallocateTarget::All,
317            }
318        }
319        // `DEALLOCATE [PREPARE] name` — lowercased for unquoted,
320        // case-preserved for `"quoted"`.
321        Some(Token::Word(_) | Token::QuotedIdent(_)) => {
322            // Unwrap is safe: we just matched Word/QuotedIdent.
323            let name = cur.eat_identifier().expect("identifier after DEALLOCATE");
324            Statement::Deallocate {
325                target: DeallocateTarget::Name(name),
326            }
327        }
328        // Bare `DEALLOCATE` or `DEALLOCATE PREPARE` alone is
329        // malformed — PostgreSQL requires a target. Fall through so
330        // the server surfaces the syntax error rather than silently
331        // succeeding with a synthetic response.
332        _ => Statement::Other,
333    }
334}
335
336// ---------------------------------------------------------------------------
337// BEGIN / START TRANSACTION
338// ---------------------------------------------------------------------------
339
340fn parse_begin(cur: &mut Cursor<'_>) -> Statement {
341    // Consume the leading keyword and remember which one it was:
342    // `START` requires a following `TRANSACTION`; `BEGIN` accepts an
343    // optional `WORK` or `TRANSACTION` keyword.
344    let is_start = matches!(cur.peek(), Some(Token::Word(w)) if w == "start");
345    cur.advance();
346
347    if is_start {
348        // `START` on its own (or `START WORK`, `START READ ONLY`,
349        // ...) is not valid SQL — PostgreSQL only accepts `START
350        // TRANSACTION [...]`. Fall through to `Other` so the server
351        // surfaces the syntax error to the client instead of us
352        // fabricating a `Begin` and routing malformed `START READ
353        // ONLY` to a replica.
354        if !cur.eat_word("transaction") {
355            return Statement::Other;
356        }
357    } else {
358        // BEGIN accepts an optional trailing WORK or TRANSACTION
359        // noise word; neither changes semantics, both are skipped.
360        let _ = cur.eat_word("work") || cur.eat_word("transaction");
361    }
362
363    Statement::Begin {
364        options: parse_transaction_options(cur),
365    }
366}
367
368/// Scan the remaining tokens for transaction-mode keywords, collecting
369/// `READ ONLY` / `READ WRITE` into [`TransactionOptions`]. Other
370/// transaction-mode tokens (`ISOLATION LEVEL SERIALIZABLE`,
371/// `DEFERRABLE`, comma separators) are skipped without error — the
372/// router only cares about the read/write flag.
373///
374/// Crucially, a bare `READ` without a following `ONLY`/`WRITE` (as in
375/// `ISOLATION LEVEL READ COMMITTED` or `REPEATABLE READ`) does not
376/// break the scan: the loop simply continues, so the later `READ ONLY`
377/// in `ISOLATION LEVEL REPEATABLE READ READ ONLY` is still picked up.
378fn parse_transaction_options(cur: &mut Cursor<'_>) -> TransactionOptions {
379    let mut opts = TransactionOptions::default();
380    while let Some(tok) = cur.peek() {
381        match tok {
382            Token::Word(w) if w == "read" => {
383                cur.advance();
384                match cur.peek() {
385                    Some(Token::Word(w)) if w == "only" => {
386                        cur.advance();
387                        opts.read_only = Some(true);
388                    }
389                    Some(Token::Word(w)) if w == "write" => {
390                        cur.advance();
391                        opts.read_only = Some(false);
392                    }
393                    // `READ` was a decoy from an isolation-level
394                    // clause — don't touch read_only, keep scanning.
395                    _ => {}
396                }
397            }
398            _ => {
399                cur.advance();
400            }
401        }
402    }
403    opts
404}
405
406// ---------------------------------------------------------------------------
407// WITH <cte> ... <statement>
408// ---------------------------------------------------------------------------
409
410/// Scan past CTE body parens at depth zero to find the wrapped
411/// statement's leading keyword. A `WITH` query that isn't followed by
412/// a recognised DML keyword returns `Other` — PostgreSQL would reject
413/// it too.
414fn parse_cte_wrapped(cur: &mut Cursor<'_>) -> Statement {
415    cur.advance(); // WITH
416    let mut depth = 0u32;
417    while let Some(t) = cur.advance() {
418        match t {
419            Token::LParen => depth += 1,
420            Token::RParen => depth = depth.saturating_sub(1),
421            Token::Word(w) if depth == 0 => match w.as_str() {
422                "select" | "table" | "values" => return Statement::Select,
423                "insert" => return Statement::Insert,
424                "update" => return Statement::Update,
425                "delete" | "truncate" => return Statement::Delete,
426                _ => {}
427            },
428            _ => {}
429        }
430    }
431    Statement::Other
432}
433
434// ---------------------------------------------------------------------------
435// Tests
436// ---------------------------------------------------------------------------
437
438#[cfg(test)]
439mod tests {
440    use super::*;
441
442    // ---- LISTEN ----------------------------------------------------------
443
444    #[test]
445    fn listen_unquoted() {
446        assert_eq!(
447            parse("LISTEN my_channel"),
448            Statement::Listen {
449                channel: "my_channel".into()
450            }
451        );
452    }
453
454    #[test]
455    fn listen_quoted_preserves_case() {
456        assert_eq!(
457            parse(r#"LISTEN "MyChannel""#),
458            Statement::Listen {
459                channel: "MyChannel".into()
460            }
461        );
462    }
463
464    #[test]
465    fn listen_without_channel_is_other() {
466        // Malformed `LISTEN` with no following identifier.
467        assert_eq!(parse("LISTEN"), Statement::Other);
468    }
469
470    // ---- UNLISTEN --------------------------------------------------------
471
472    #[test]
473    fn unlisten_star() {
474        assert_eq!(
475            parse("UNLISTEN *"),
476            Statement::Unlisten {
477                target: UnlistenTarget::Star
478            }
479        );
480    }
481
482    #[test]
483    fn unlisten_quoted_star_is_channel_not_wildcard() {
484        // The quoted form is a literal identifier named `*`, not the
485        // wildcard.
486        assert_eq!(
487            parse(r#"UNLISTEN "*""#),
488            Statement::Unlisten {
489                target: UnlistenTarget::Channel("*".into())
490            }
491        );
492    }
493
494    #[test]
495    fn unlisten_channel_name() {
496        assert_eq!(
497            parse("UNLISTEN my_channel"),
498            Statement::Unlisten {
499                target: UnlistenTarget::Channel("my_channel".into())
500            }
501        );
502    }
503
504    // ---- SET -------------------------------------------------------------
505
506    #[test]
507    fn set_session_default() {
508        assert_eq!(
509            parse("SET work_mem = '256MB'"),
510            Statement::Set {
511                scope: SetScope::Session,
512                parameter: "work_mem".into(),
513                value: SetValue::Literal("256mb".into()),
514            }
515        );
516    }
517
518    #[test]
519    fn set_to_syntax() {
520        assert_eq!(
521            parse("SET search_path TO public"),
522            Statement::Set {
523                scope: SetScope::Session,
524                parameter: "search_path".into(),
525                value: SetValue::Literal("public".into()),
526            }
527        );
528    }
529
530    #[test]
531    fn set_local_scope() {
532        assert_eq!(
533            parse("SET LOCAL work_mem = '1MB'"),
534            Statement::Set {
535                scope: SetScope::Local,
536                parameter: "work_mem".into(),
537                value: SetValue::Literal("1mb".into()),
538            }
539        );
540    }
541
542    #[test]
543    fn set_session_scope_explicit() {
544        assert_eq!(
545            parse("SET SESSION work_mem = '1GB'"),
546            Statement::Set {
547                scope: SetScope::Session,
548                parameter: "work_mem".into(),
549                value: SetValue::Literal("1gb".into()),
550            }
551        );
552    }
553
554    #[test]
555    fn set_default_value() {
556        assert_eq!(
557            parse("SET default_transaction_read_only TO DEFAULT"),
558            Statement::Set {
559                scope: SetScope::Session,
560                parameter: "default_transaction_read_only".into(),
561                value: SetValue::Default,
562            }
563        );
564    }
565
566    #[test]
567    fn set_quoted_parameter_preserves_case() {
568        assert_eq!(
569            parse(r#"SET "MyVar" = 'value'"#),
570            Statement::Set {
571                scope: SetScope::Session,
572                parameter: "MyVar".into(),
573                value: SetValue::Literal("value".into()),
574            }
575        );
576    }
577
578    /// Regression guard: a SET whose value has a leading sign
579    /// character must still parse as `Statement::Set` with the
580    /// parameter name populated — not collapse to `Other`. Otherwise
581    /// `track_set_reset` never inserts the parameter into
582    /// `dirty_vars` and `reset_connection` fails to RESET it on
583    /// checkin, leaking the modified value to the next pool client.
584    #[test]
585    fn set_negative_number() {
586        assert_eq!(
587            parse("SET work_mem = -1"),
588            Statement::Set {
589                scope: SetScope::Session,
590                parameter: "work_mem".into(),
591                value: SetValue::Literal("1".into()),
592            }
593        );
594    }
595
596    #[test]
597    fn set_positive_sign_number() {
598        assert_eq!(
599            parse("SET work_mem = +5"),
600            Statement::Set {
601                scope: SetScope::Session,
602                parameter: "work_mem".into(),
603                value: SetValue::Literal("5".into()),
604            }
605        );
606    }
607
608    #[test]
609    fn set_negative_with_to_syntax() {
610        assert_eq!(
611            parse("SET seed TO -1"),
612            Statement::Set {
613                scope: SetScope::Session,
614                parameter: "seed".into(),
615                value: SetValue::Literal("1".into()),
616            }
617        );
618    }
619
620    #[test]
621    fn set_local_negative_number() {
622        // LOCAL scope must still be tracked; otherwise the
623        // transaction-level GUC change leaks the wrong way.
624        assert_eq!(
625            parse("SET LOCAL work_mem = -1"),
626            Statement::Set {
627                scope: SetScope::Local,
628                parameter: "work_mem".into(),
629                value: SetValue::Literal("1".into()),
630            }
631        );
632    }
633
634    // ---- SET TRANSACTION -------------------------------------------------
635
636    #[test]
637    fn set_transaction_read_write() {
638        assert_eq!(
639            parse("SET TRANSACTION READ WRITE"),
640            Statement::SetTransaction {
641                options: TransactionOptions {
642                    read_only: Some(false)
643                }
644            }
645        );
646    }
647
648    #[test]
649    fn set_session_characteristics() {
650        assert_eq!(
651            parse("SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE"),
652            Statement::SetTransaction {
653                options: TransactionOptions {
654                    read_only: Some(false)
655                }
656            }
657        );
658    }
659
660    #[test]
661    fn set_session_characteristics_malformed_is_other() {
662        assert_eq!(
663            parse("SET SESSION CHARACTERISTICS work_mem = '1GB'"),
664            Statement::Other
665        );
666    }
667
668    // ---- RESET -----------------------------------------------------------
669
670    #[test]
671    fn reset_all() {
672        assert_eq!(
673            parse("RESET ALL"),
674            Statement::Reset {
675                target: ResetTarget::All
676            }
677        );
678    }
679
680    #[test]
681    fn reset_parameter() {
682        assert_eq!(
683            parse("RESET work_mem"),
684            Statement::Reset {
685                target: ResetTarget::Parameter("work_mem".into())
686            }
687        );
688    }
689
690    // ---- DISCARD ---------------------------------------------------------
691
692    #[test]
693    fn discard_variants() {
694        assert_eq!(
695            parse("DISCARD ALL"),
696            Statement::Discard {
697                target: DiscardTarget::All
698            }
699        );
700        assert_eq!(
701            parse("DISCARD PLANS"),
702            Statement::Discard {
703                target: DiscardTarget::Plans
704            }
705        );
706        assert_eq!(
707            parse("DISCARD SEQUENCES"),
708            Statement::Discard {
709                target: DiscardTarget::Sequences
710            }
711        );
712        assert_eq!(
713            parse("DISCARD TEMPORARY"),
714            Statement::Discard {
715                target: DiscardTarget::Temp
716            }
717        );
718        assert_eq!(
719            parse("DISCARD TEMP"),
720            Statement::Discard {
721                target: DiscardTarget::Temp
722            }
723        );
724    }
725
726    #[test]
727    fn discard_malformed_is_other() {
728        assert_eq!(parse("DISCARD"), Statement::Other);
729        assert_eq!(parse("DISCARD FOO"), Statement::Other);
730    }
731
732    // ---- DEALLOCATE ------------------------------------------------------
733
734    #[test]
735    fn deallocate_named() {
736        assert_eq!(
737            parse("DEALLOCATE my_stmt"),
738            Statement::Deallocate {
739                target: DeallocateTarget::Name("my_stmt".into())
740            }
741        );
742    }
743
744    #[test]
745    fn deallocate_all() {
746        assert_eq!(
747            parse("DEALLOCATE ALL"),
748            Statement::Deallocate {
749                target: DeallocateTarget::All
750            }
751        );
752    }
753
754    #[test]
755    fn deallocate_prepare_noise_keyword() {
756        // The optional `PREPARE` keyword is part of the grammar but
757        // contributes no semantics; both forms collapse to the same
758        // variant.
759        assert_eq!(
760            parse("DEALLOCATE PREPARE my_stmt"),
761            Statement::Deallocate {
762                target: DeallocateTarget::Name("my_stmt".into())
763            }
764        );
765        assert_eq!(
766            parse("DEALLOCATE PREPARE ALL"),
767            Statement::Deallocate {
768                target: DeallocateTarget::All
769            }
770        );
771    }
772
773    #[test]
774    fn deallocate_mixed_case() {
775        assert_eq!(
776            parse("Deallocate Prepare My_Stmt"),
777            Statement::Deallocate {
778                target: DeallocateTarget::Name("my_stmt".into())
779            }
780        );
781        assert_eq!(
782            parse("deallocate all"),
783            Statement::Deallocate {
784                target: DeallocateTarget::All
785            }
786        );
787    }
788
789    #[test]
790    fn deallocate_quoted_identifier_preserves_case() {
791        assert_eq!(
792            parse(r#"DEALLOCATE "MyStmt""#),
793            Statement::Deallocate {
794                target: DeallocateTarget::Name("MyStmt".into())
795            }
796        );
797        assert_eq!(
798            parse(r#"DEALLOCATE PREPARE "MyStmt""#),
799            Statement::Deallocate {
800                target: DeallocateTarget::Name("MyStmt".into())
801            }
802        );
803    }
804
805    /// A quoted `"ALL"` is a literal identifier, not the wildcard
806    /// keyword — mirrors the `UNLISTEN "*"` case. PostgreSQL itself
807    /// treats the unquoted `ALL` as a reserved keyword in this
808    /// position.
809    #[test]
810    fn deallocate_quoted_all_is_name_not_wildcard() {
811        assert_eq!(
812            parse(r#"DEALLOCATE "ALL""#),
813            Statement::Deallocate {
814                target: DeallocateTarget::Name("ALL".into())
815            }
816        );
817    }
818
819    #[test]
820    fn deallocate_malformed_is_other() {
821        // Bare DEALLOCATE — no target.
822        assert_eq!(parse("DEALLOCATE"), Statement::Other);
823        // DEALLOCATE PREPARE without a target.
824        assert_eq!(parse("DEALLOCATE PREPARE"), Statement::Other);
825    }
826
827    // ---- BEGIN / START ---------------------------------------------------
828
829    #[test]
830    fn begin_plain() {
831        assert_eq!(
832            parse("BEGIN"),
833            Statement::Begin {
834                options: TransactionOptions::default()
835            }
836        );
837    }
838
839    #[test]
840    fn begin_read_only() {
841        assert_eq!(
842            parse("BEGIN READ ONLY"),
843            Statement::Begin {
844                options: TransactionOptions {
845                    read_only: Some(true)
846                }
847            }
848        );
849    }
850
851    #[test]
852    fn begin_read_write() {
853        assert_eq!(
854            parse("BEGIN READ WRITE"),
855            Statement::Begin {
856                options: TransactionOptions {
857                    read_only: Some(false)
858                }
859            }
860        );
861    }
862
863    #[test]
864    fn begin_with_isolation_before_read_only() {
865        // The `READ` inside `REPEATABLE READ` must not break the scan
866        // — the later `READ ONLY` is still picked up.
867        assert_eq!(
868            parse("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY"),
869            Statement::Begin {
870                options: TransactionOptions {
871                    read_only: Some(true)
872                }
873            }
874        );
875    }
876
877    #[test]
878    fn begin_isolation_read_committed_no_mode() {
879        // `READ COMMITTED` has no effect on the read_only flag.
880        assert_eq!(
881            parse("BEGIN ISOLATION LEVEL READ COMMITTED"),
882            Statement::Begin {
883                options: TransactionOptions { read_only: None }
884            }
885        );
886    }
887
888    #[test]
889    fn start_transaction_read_only() {
890        assert_eq!(
891            parse("START TRANSACTION READ ONLY"),
892            Statement::Begin {
893                options: TransactionOptions {
894                    read_only: Some(true)
895                }
896            }
897        );
898    }
899
900    /// Regression guard: `START` without a following `TRANSACTION`
901    /// must parse as `Other`, not `Begin`. Misclassifying it as
902    /// `Begin` lets the router send `START READ ONLY` to a replica
903    /// where PostgreSQL rejects it with a syntax error the client
904    /// doesn't expect.
905    #[test]
906    fn start_without_transaction_is_other() {
907        assert_eq!(parse("START"), Statement::Other);
908        assert_eq!(parse("START WORK"), Statement::Other);
909        assert_eq!(parse("START READ ONLY"), Statement::Other);
910        assert_eq!(parse("START WORK READ ONLY"), Statement::Other);
911    }
912
913    // ---- COMMIT / ROLLBACK -----------------------------------------------
914
915    #[test]
916    fn commit_aliases() {
917        assert_eq!(parse("COMMIT"), Statement::Commit);
918        assert_eq!(parse("END"), Statement::Commit);
919    }
920
921    #[test]
922    fn rollback_aliases() {
923        assert_eq!(parse("ROLLBACK"), Statement::Rollback);
924        assert_eq!(parse("ABORT"), Statement::Rollback);
925    }
926
927    // ---- DML -------------------------------------------------------------
928
929    #[test]
930    fn select_variants() {
931        assert_eq!(parse("SELECT 1"), Statement::Select);
932        assert_eq!(parse("TABLE t"), Statement::Select);
933        assert_eq!(parse("VALUES (1)"), Statement::Select);
934    }
935
936    #[test]
937    fn dml_variants() {
938        assert_eq!(parse("INSERT INTO t VALUES (1)"), Statement::Insert);
939        assert_eq!(parse("UPDATE t SET x = 1"), Statement::Update);
940        assert_eq!(parse("DELETE FROM t"), Statement::Delete);
941        assert_eq!(parse("TRUNCATE t"), Statement::Delete);
942        assert_eq!(parse("COPY t FROM stdin"), Statement::Copy);
943    }
944
945    // ---- WITH CTE --------------------------------------------------------
946
947    #[test]
948    fn with_cte_select() {
949        assert_eq!(
950            parse("WITH cte AS (SELECT 1) SELECT * FROM cte"),
951            Statement::Select
952        );
953    }
954
955    #[test]
956    fn with_cte_insert() {
957        assert_eq!(
958            parse("WITH cte AS (SELECT 1) INSERT INTO t SELECT * FROM cte"),
959            Statement::Insert
960        );
961    }
962
963    #[test]
964    fn with_recursive() {
965        assert_eq!(
966            parse("WITH RECURSIVE tree AS (SELECT 1) SELECT * FROM tree"),
967            Statement::Select
968        );
969    }
970
971    // ---- Degenerate ------------------------------------------------------
972
973    #[test]
974    fn empty_input() {
975        assert_eq!(parse(""), Statement::Other);
976        assert_eq!(parse("   "), Statement::Other);
977    }
978
979    #[test]
980    fn only_comment() {
981        assert_eq!(parse("-- just a comment"), Statement::Other);
982    }
983
984    #[test]
985    fn ddl_is_other() {
986        assert_eq!(parse("CREATE TABLE t (id int)"), Statement::Other);
987    }
988
989    // ---- is_read_only / is_read_write_override on the AST ---------------
990
991    #[test]
992    fn is_read_only_pattern() {
993        assert!(matches!(
994            parse("BEGIN READ ONLY"),
995            Statement::Begin {
996                options: TransactionOptions {
997                    read_only: Some(true)
998                }
999            }
1000        ));
1001        assert!(!matches!(
1002            parse("BEGIN"),
1003            Statement::Begin {
1004                options: TransactionOptions {
1005                    read_only: Some(true)
1006                }
1007            }
1008        ));
1009    }
1010
1011    #[test]
1012    fn is_read_write_override_covers_all_paths() {
1013        assert!(parse("BEGIN READ WRITE").is_read_write_override());
1014        assert!(parse("SET TRANSACTION READ WRITE").is_read_write_override());
1015        assert!(
1016            parse("SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE").is_read_write_override()
1017        );
1018        assert!(parse("SET default_transaction_read_only = off").is_read_write_override());
1019        assert!(parse("SET default_transaction_read_only = 'off'").is_read_write_override());
1020        assert!(parse("SET default_transaction_read_only TO DEFAULT").is_read_write_override());
1021
1022        assert!(!parse("BEGIN READ ONLY").is_read_write_override());
1023        assert!(!parse("BEGIN").is_read_write_override());
1024        assert!(!parse("SET default_transaction_read_only = on").is_read_write_override());
1025        assert!(!parse("SET work_mem = '1MB'").is_read_write_override());
1026        assert!(!parse("SELECT 1").is_read_write_override());
1027    }
1028
1029    /// Regression: `RESET default_transaction_read_only` is
1030    /// semantically identical to `SET ... TO DEFAULT` (both revert
1031    /// the GUC to the compiled default, which is `off` / read-write)
1032    /// and must be flagged as a read-write override so the router
1033    /// rejects it on replica-routed transactions. Without this, a
1034    /// client could issue RESET to silently flip the connection back
1035    /// to read-write and leak that state to the next pool user.
1036    #[test]
1037    fn reset_default_transaction_read_only_is_override() {
1038        assert!(parse("RESET default_transaction_read_only").is_read_write_override());
1039        assert!(parse("reset DEFAULT_TRANSACTION_READ_ONLY").is_read_write_override());
1040    }
1041
1042    /// Regression: `RESET ALL` sweeps every session setting including
1043    /// `default_transaction_read_only`, so it has the same effect as
1044    /// the targeted RESET above and must be rejected the same way.
1045    #[test]
1046    fn reset_all_is_override() {
1047        assert!(parse("RESET ALL").is_read_write_override());
1048        assert!(parse("reset all").is_read_write_override());
1049    }
1050
1051    /// Narrow check: a RESET of an unrelated GUC is NOT an override.
1052    /// Only `default_transaction_read_only` and `ALL` matter.
1053    #[test]
1054    fn reset_other_parameter_is_not_override() {
1055        assert!(!parse("RESET work_mem").is_read_write_override());
1056        assert!(!parse("RESET search_path").is_read_write_override());
1057    }
1058}