Skip to main content

halephant_core/sql/
ast.rs

1//! Minimal SQL statement AST.
2//!
3//! Each variant captures exactly the fields halephant needs to route,
4//! intercept, or classify a statement. Anything outside that set
5//! collapses into `Statement::Other`, so consumers can rely on
6//! exhaustive pattern matches without a parser that understands the
7//! full PostgreSQL grammar.
8//!
9//! This is deliberately not a faithful AST: nested expressions, join
10//! trees, projections, and ordering clauses are all invisible to it.
11//! The design goal is "enough structure that a caller never needs a
12//! second helper function to pull a value out of the result."
13
14/// A parsed SQL statement.
15///
16/// The parser only inspects leading tokens, so multi-statement
17/// queries are classified by their first statement.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum Statement {
20    /// `LISTEN channel`. The channel name is lowercased for unquoted
21    /// identifiers and case-preserved for `"quoted"` identifiers —
22    /// matching PostgreSQL's own rules.
23    Listen { channel: String },
24
25    /// `UNLISTEN *` or `UNLISTEN channel`.
26    Unlisten { target: UnlistenTarget },
27
28    /// `SET [SESSION | LOCAL] parameter (= | TO) value` — a regular
29    /// GUC assignment.
30    ///
31    /// `SET TRANSACTION ...` and `SET SESSION CHARACTERISTICS AS
32    /// TRANSACTION ...` are parsed as [`Statement::SetTransaction`]
33    /// instead; those configure transaction characteristics, not a
34    /// parameter value.
35    Set {
36        scope: SetScope,
37        parameter: String,
38        value: SetValue,
39    },
40
41    /// `SET TRANSACTION <modes>` (for the current transaction) or
42    /// `SET SESSION CHARACTERISTICS AS TRANSACTION <modes>` (session
43    /// defaults for future transactions). Both share the same
44    /// transaction-mode grammar, so they flatten to a single variant.
45    SetTransaction { options: TransactionOptions },
46
47    /// `RESET ALL` or `RESET parameter`.
48    Reset { target: ResetTarget },
49
50    /// `DISCARD ALL | PLANS | SEQUENCES | TEMPORARY | TEMP`.
51    ///
52    /// The subtarget matters: only `DISCARD ALL` drops prepared
53    /// statements (via its embedded `DEALLOCATE ALL`) and resets
54    /// session GUCs. `PLANS` only invalidates cached query plans —
55    /// the prepared statements themselves persist. `SEQUENCES` and
56    /// `TEMPORARY` do not touch the pool state halephant tracks.
57    /// See [`DiscardTarget`] for the full list.
58    Discard { target: DiscardTarget },
59
60    /// `DEALLOCATE [PREPARE] (name | ALL)`.
61    ///
62    /// The `PREPARE` keyword between `DEALLOCATE` and the target is
63    /// optional noise in PostgreSQL's grammar; the parser collapses
64    /// both forms to the same variant.
65    ///
66    /// Halephant intercepts this at the transaction layer: the server
67    /// only knows the canonical (hashed) name halephant assigned
68    /// during Parse rewriting, so a raw `DEALLOCATE my_stmt` would
69    /// error out with "prepared statement does not exist". The
70    /// interceptor resolves the client-side name against
71    /// `ClientPrepared`, releases the refcount in the global
72    /// `StatementStore`, and synthesises a `CommandComplete` response
73    /// without forwarding to the server — the actual server-side
74    /// statement is eventually reclaimed by `ServerPrepared`'s LRU.
75    Deallocate { target: DeallocateTarget },
76
77    /// `BEGIN [transaction_mode ...]` or `START TRANSACTION
78    /// [transaction_mode ...]`. Folded to a single variant since
79    /// PostgreSQL treats them identically.
80    Begin { options: TransactionOptions },
81
82    /// `COMMIT` (or its `END` alias).
83    Commit,
84
85    /// `ROLLBACK` or `ABORT` (including `ROLLBACK TO SAVEPOINT ...`).
86    Rollback,
87
88    /// `SELECT ...`, `TABLE ...`, `VALUES ...`, or a
89    /// `WITH ... SELECT/TABLE/VALUES`.
90    Select,
91
92    /// `INSERT ...`, or a `WITH ... INSERT`.
93    Insert,
94
95    /// `UPDATE ...`, or a `WITH ... UPDATE`.
96    Update,
97
98    /// `DELETE ...`, `TRUNCATE ...`, or a `WITH ... DELETE`.
99    Delete,
100
101    /// `COPY ...`.
102    Copy,
103
104    /// Anything else: DDL, empty input, bare punctuation, statements
105    /// whose leading keyword is not recognised. Halephant forwards
106    /// these without further inspection.
107    Other,
108}
109
110impl Statement {
111    /// Returns `true` when the statement itself is read-only — currently
112    /// only plain `SELECT`. This is a *statement* property, independent
113    /// of any transaction-level read-only mode the caller tracks
114    /// separately.
115    pub fn is_read_only(&self) -> bool {
116        matches!(self, Self::Select)
117    }
118
119    /// Returns `true` when the statement attempts to switch a read-only
120    /// transaction back to read-write. Covers every variant that can
121    /// flip the effective read/write mode:
122    ///
123    /// - `BEGIN READ WRITE` / `START TRANSACTION READ WRITE`
124    /// - `SET TRANSACTION READ WRITE`
125    /// - `SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE`
126    /// - `SET default_transaction_read_only = <false-ish>` or
127    ///   `TO DEFAULT` (the compiled default for that GUC is `off`,
128    ///   so resetting it to default means read-write)
129    /// - `RESET default_transaction_read_only` (identical effect to
130    ///   `SET ... TO DEFAULT` — both revert to the compiled default)
131    /// - `RESET ALL` (sweeps every session setting, including
132    ///   `default_transaction_read_only`)
133    ///
134    /// Halephant uses this to reject writes on replica-routed
135    /// transactions without having to re-parse the statement. Missing
136    /// any of the above would let a client silently restore
137    /// read-write on a replica-routed connection.
138    pub fn is_read_write_override(&self) -> bool {
139        match self {
140            Self::Begin { options } | Self::SetTransaction { options } => {
141                options.read_only == Some(false)
142            }
143            Self::Set {
144                parameter, value, ..
145            } if parameter == "default_transaction_read_only" => match value {
146                SetValue::Default => true,
147                SetValue::Literal(s) => crate::sql::as_boolean(s) == Some(false),
148            },
149            Self::Reset {
150                target: ResetTarget::Parameter(name),
151            } if name == "default_transaction_read_only" => true,
152            Self::Reset {
153                target: ResetTarget::All,
154            } => true,
155            _ => false,
156        }
157    }
158}
159
160/// Target of an `UNLISTEN`: a specific channel name or the wildcard.
161#[derive(Debug, Clone, PartialEq, Eq)]
162pub enum UnlistenTarget {
163    /// `UNLISTEN *` — drop all subscriptions. Note that a double-quoted
164    /// `UNLISTEN "*"` is parsed as `Channel("*")`, not `Star`, because
165    /// the quoted form is a literal identifier named `*`.
166    Star,
167    /// `UNLISTEN channel`. Lowercased for unquoted, case-preserved
168    /// for `"quoted"`.
169    Channel(String),
170}
171
172/// Visibility scope of a `SET` assignment.
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub enum SetScope {
175    /// `SET [SESSION] parameter = value` — applies to the current
176    /// session until explicitly reset.
177    Session,
178    /// `SET LOCAL parameter = value` — applies only within the current
179    /// transaction and is discarded on COMMIT/ROLLBACK.
180    Local,
181}
182
183/// Value on the right-hand side of a `SET parameter (= | TO) ...`.
184///
185/// Literals are canonicalised by the lexer: unquoted keywords and
186/// single-quoted strings are lowercased (so `'Off'` and `off` both
187/// arrive as `"off"`), and numeric literals preserve their original
188/// digits. Double-quoted identifiers are never accepted as values.
189#[derive(Debug, Clone, PartialEq, Eq)]
190pub enum SetValue {
191    /// A concrete literal value. Pass this to [`crate::sql::as_boolean`]
192    /// to interpret it as a PostgreSQL boolean.
193    Literal(String),
194    /// `SET parameter (= | TO) DEFAULT` — reset to the compiled-in
195    /// default. This is syntactically distinct from a literal because
196    /// the caller often needs to resolve "default" against the GUC's
197    /// compiled default.
198    Default,
199}
200
201/// Target of a `RESET`.
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub enum ResetTarget {
204    /// `RESET ALL` — reset every session-level setting.
205    All,
206    /// `RESET parameter` — reset a single parameter.
207    Parameter(String),
208}
209
210/// Target of a `DISCARD`. PostgreSQL's `DISCARD ALL` is defined as a
211/// macro expansion of the other `DISCARD` variants plus `DEALLOCATE
212/// ALL`, `RESET ALL`, `CLOSE ALL`, `UNLISTEN *`, and
213/// `pg_advisory_unlock_all()`. The distinction matters because
214/// halephant's per-connection pool state tracking needs to react to
215/// `ALL` (clear prepared statements and dirty GUCs) but not to the
216/// narrower forms.
217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
218pub enum DiscardTarget {
219    /// `DISCARD ALL` — full session reset. Drops prepared statements
220    /// (DEALLOCATE ALL), resets every GUC (RESET ALL), closes cursors,
221    /// and drops temp tables. Halephant must clear both its
222    /// `ServerPrepared` tracker and its `dirty_vars` set on the
223    /// affected connection.
224    All,
225    /// `DISCARD PLANS` — releases cached query plans only. The
226    /// prepared statements themselves remain registered on the
227    /// backend; the next `Bind` will trigger re-planning transparently,
228    /// so halephant's pool state is unaffected.
229    Plans,
230    /// `DISCARD SEQUENCES` — discards cached sequence-related state.
231    /// Has no bearing on halephant's pool tracking.
232    Sequences,
233    /// `DISCARD TEMPORARY` / `DISCARD TEMP` — drops temp tables. Has
234    /// no bearing on halephant's pool tracking.
235    Temp,
236}
237
238/// Target of a `DEALLOCATE`.
239#[derive(Debug, Clone, PartialEq, Eq)]
240pub enum DeallocateTarget {
241    /// `DEALLOCATE ALL` / `DEALLOCATE PREPARE ALL` — drop every
242    /// prepared statement the client has registered.
243    All,
244    /// `DEALLOCATE name` / `DEALLOCATE PREPARE name` — drop a single
245    /// named prepared statement. The name is the client-side
246    /// identifier from the original `Parse`; halephant must resolve
247    /// it to a canonical name before touching the global store.
248    /// Lowercased for unquoted identifiers, case-preserved for
249    /// `"quoted"` identifiers, matching PostgreSQL's rules.
250    Name(String),
251}
252
253/// Transaction-mode options gathered from a `BEGIN`, `START
254/// TRANSACTION`, `SET TRANSACTION`, or `SET SESSION CHARACTERISTICS AS
255/// TRANSACTION` clause.
256///
257/// Only the fields halephant actually uses are tracked. Isolation
258/// level and deferrable flags are parsed implicitly (the parser walks
259/// past them without producing errors) but not surfaced, because
260/// nothing in the router needs them.
261#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
262pub struct TransactionOptions {
263    /// `Some(true)` for an explicit `READ ONLY`, `Some(false)` for
264    /// `READ WRITE`, `None` when neither was specified. When both
265    /// appear (malformed SQL), the *last* one wins — matching
266    /// PostgreSQL's own parser behaviour.
267    pub read_only: Option<bool>,
268}