halephant_core/sql/mod.rs
1//! Minimal SQL parser for halephant's routing and interception needs.
2//!
3//! The module is split into three layers:
4//!
5//! - `lexer`: chumsky character-level tokenizer — handles nested
6//! block comments, dollar-quoted strings, single-quoted strings with
7//! `''` escapes, and double-quoted identifiers with `""` escapes.
8//! - `parser`: a tiny hand-written recursive-descent walker over the
9//! token slice, producing a [`Statement`] AST.
10//! - `ast`: the AST — one variant per statement shape halephant
11//! cares about, with all relevant fields captured inline so
12//! consumers never need a second extraction helper.
13//!
14//! Public API is deliberately small: [`parse`] to get a [`Statement`],
15//! [`as_boolean`] to interpret a PostgreSQL boolean literal. Everything
16//! else is a method on the AST (see [`Statement::is_read_only`] and
17//! [`Statement::is_read_write_override`]).
18
19mod ast;
20mod lexer;
21mod parser;
22
23pub use ast::{
24 DeallocateTarget, DiscardTarget, ResetTarget, SetScope, SetValue, Statement,
25 TransactionOptions, UnlistenTarget,
26};
27pub use parser::parse;
28
29/// Interpret a lowercased string as a PostgreSQL boolean value.
30///
31/// PostgreSQL accepts unambiguous prefixes of `true`, `false`, `yes`,
32/// `no`, `on`, `off`, plus the numeric literals `1` and `0`. A bare
33/// `o` is rejected because it is ambiguous between `on` and `off`.
34///
35/// This helper is exposed so callers can interpret a
36/// [`SetValue::Literal`] payload — the parser itself never resolves
37/// boolean semantics, because a single GUC value might be boolean in
38/// one context and a literal string in another.
39pub fn as_boolean(val: &str) -> Option<bool> {
40 match val {
41 "t" | "tr" | "tru" | "true" | "y" | "ye" | "yes" | "on" | "1" => Some(true),
42 "f" | "fa" | "fal" | "fals" | "false" | "n" | "no" | "of" | "off" | "0" => Some(false),
43 _ => None,
44 }
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50
51 #[test]
52 fn boolean_true_values() {
53 for s in ["t", "tr", "tru", "true", "y", "ye", "yes", "on", "1"] {
54 assert_eq!(as_boolean(s), Some(true), "{s:?} should be true");
55 }
56 }
57
58 #[test]
59 fn boolean_false_values() {
60 for s in [
61 "f", "fa", "fal", "fals", "false", "n", "no", "of", "off", "0",
62 ] {
63 assert_eq!(as_boolean(s), Some(false), "{s:?} should be false");
64 }
65 }
66
67 #[test]
68 fn bare_o_is_ambiguous() {
69 assert_eq!(as_boolean("o"), None);
70 }
71
72 #[test]
73 fn invalid_boolean_rejected() {
74 for s in [
75 "", "maybe", "2", "256mb", "truth", "nope", "yep", "11", "10",
76 ] {
77 assert_eq!(as_boolean(s), None, "{s:?} should not parse");
78 }
79 }
80}