Skip to main content

sql_insight/
normalizer.rs

1//! SQL normalization — rewrite the AST so structurally identical
2//! queries hash to the same string. See [`normalize`] as the entry
3//! point.
4//!
5//! The base pass replaces every literal `Value` with a `?`
6//! placeholder, so queries that differ only in their parameter
7//! values collapse to the same string.
8//!
9//! "Every literal" is meant literally: it includes `Value`s in
10//! structurally significant positions, not just bound-parameter slots.
11//! A JSON path (`JSON_TABLE(data, '$.a')`, `JSON_EXTRACT(data, '$.a')`),
12//! a `CAST(x AS DATE FORMAT 'YYYY-MM-DD')` format string, the
13//! `TABLESAMPLE (BUCKET 3 OUT OF 10)` / `(10 PERCENT)` counts, and
14//! `LIMIT` / `OFFSET` are all rewritten to `?`. So two queries differing
15//! only in such a literal — e.g. selecting a different JSON field or
16//! sampling a different bucket — collapse to the same normalized string.
17//!
18//! Three opt-in toggles ([`NormalizerOptions`]) further collapse
19//! repetitive shapes:
20//!
21//! - [`unify_in_list`](NormalizerOptions::unify_in_list):
22//!   `IN (1, 2, 3)` → `IN (...)`.
23//! - [`unify_values`](NormalizerOptions::unify_values):
24//!   `VALUES (1, 2, 3), (4, 5, 6)` → `VALUES (...)`.
25//! - [`alphabetize_insert_columns`](NormalizerOptions::alphabetize_insert_columns):
26//!   `INSERT INTO t (c, b, a) VALUES (...)` →
27//!   `INSERT INTO t (a, b, c) VALUES (...)`, only when VALUES is
28//!   unified.
29//!
30//! Output is one `String` per parsed statement, formatted by
31//! sqlparser's `Display` after the rewrite.
32
33use std::ops::{ControlFlow, Deref};
34
35use crate::error::Error;
36use sqlparser::ast::{Expr, Insert, Statement, VisitMut, VisitorMut};
37use sqlparser::ast::{Parens, Query, SetExpr, TopQuantity, Value, ValueWithSpan};
38use sqlparser::dialect::Dialect;
39use sqlparser::parser::Parser;
40use std::ops::DerefMut;
41
42/// Parse `sql` under `dialect` and normalize each statement with
43/// default options (literal-to-`?` placeholder substitution only).
44///
45/// ## Example
46///
47/// ```rust
48/// use sql_insight::sqlparser::dialect::GenericDialect;
49///
50/// let dialect = GenericDialect {};
51/// let sql = "SELECT a FROM t1 WHERE b = 1 AND c in (2, 3) AND d LIKE '%foo'";
52/// let result = sql_insight::normalizer::normalize(&dialect, sql).unwrap();
53/// assert_eq!(result, ["SELECT a FROM t1 WHERE b = ? AND c IN (?, ?) AND d LIKE ?"]);
54/// ```
55pub fn normalize(dialect: &dyn Dialect, sql: &str) -> Result<Vec<String>, Error> {
56    Normalizer::normalize(dialect, sql, NormalizerOptions::new())
57}
58
59/// Parse `sql` under `dialect` and normalize each statement,
60/// applying any extra collapses enabled in `options`.
61///
62/// ## Example
63///
64/// ```rust
65/// use sql_insight::sqlparser::dialect::GenericDialect;
66/// use sql_insight::normalizer::{normalize_with_options, NormalizerOptions};
67///
68/// let dialect = GenericDialect {};
69/// let sql = "SELECT a FROM t1 WHERE b = 1 AND c in (2, 3, 4)";
70/// let result = normalize_with_options(&dialect, sql, NormalizerOptions::new().with_unify_in_list(true)).unwrap();
71/// assert_eq!(result, ["SELECT a FROM t1 WHERE b = ? AND c IN (...)"]);
72/// ```
73pub fn normalize_with_options(
74    dialect: &dyn Dialect,
75    sql: &str,
76    options: NormalizerOptions,
77) -> Result<Vec<String>, Error> {
78    Normalizer::normalize(dialect, sql, options)
79}
80
81/// Toggles for [`normalize_with_options`]. Defaults to all `false`
82/// (placeholder substitution only).
83#[derive(Default, Clone)]
84pub struct NormalizerOptions {
85    /// Unify IN lists to a single form when all elements are literal values.
86    /// For example, `IN (1, 2, 3)` becomes `IN (...)`.
87    pub unify_in_list: bool,
88    /// Unify VALUES lists to a single form when all elements are literal values.
89    /// For example, `VALUES (1, 2, 3), (4, 5, 6)` becomes `VALUES (...)`.
90    pub unify_values: bool,
91    /// Alphabetize column lists for INSERT statements with a VALUES expression
92    /// that gets unified.
93    /// For example, `INSERT INTO t(c, b, a)` becomes `INSERT INTO t(a, b, c)`.
94    pub alphabetize_insert_columns: bool,
95}
96
97impl NormalizerOptions {
98    pub fn new() -> Self {
99        Self::default()
100    }
101
102    pub fn with_unify_in_list(mut self, unify_in_list: bool) -> Self {
103        self.unify_in_list = unify_in_list;
104        self
105    }
106
107    pub fn with_unify_values(mut self, unify_values: bool) -> Self {
108        self.unify_values = unify_values;
109        self
110    }
111
112    pub fn with_alphabetize_insert_columns(mut self, alphabetize_insert_columns: bool) -> Self {
113        self.alphabetize_insert_columns = alphabetize_insert_columns;
114        self
115    }
116}
117
118/// `VisitorMut` impl that performs the normalization rewrite.
119/// Most callers go through [`normalize`] / [`normalize_with_options`]
120/// or [`Normalizer::normalize`] (which constructs and drives this
121/// visitor internally). Use the struct directly only when you want
122/// to integrate the rewrite into a larger AST traversal.
123#[derive(Default)]
124pub struct Normalizer {
125    pub options: NormalizerOptions,
126}
127
128impl VisitorMut for Normalizer {
129    type Break = ();
130
131    fn post_visit_query(&mut self, query: &mut Query) -> ControlFlow<Self::Break> {
132        // `SELECT TOP 10`'s quantity is a bare `u64` (`TopQuantity::Constant`),
133        // not a `Value`, so the visitor's literal pass doesn't reach it — unlike
134        // `TOP (expr)` / `LIMIT`. Normalize it here so `TOP 10` becomes `TOP ?`.
135        normalize_top(query.body.deref_mut());
136        if let SetExpr::Values(values) = query.body.deref_mut() {
137            if self.options.unify_values {
138                let rows = &mut values.rows;
139                if rows.is_empty()
140                    || rows.iter().all(|row| {
141                        row.is_empty() || row.iter().all(|expr| matches!(expr, Expr::Value(_)))
142                    })
143                {
144                    // `Values::rows` is `Vec<Parens<Vec<Expr>>>` (each row
145                    // tracks its own parentheses tokens); wrap the collapsed
146                    // sentinel row accordingly.
147                    *rows = vec![Parens::with_empty_span(vec![Expr::Value(
148                        Value::Placeholder("...".into()).with_empty_span(),
149                    )])];
150                }
151            }
152        }
153        ControlFlow::Continue(())
154    }
155
156    fn post_visit_statement(
157        &mut self,
158        stmt: &mut sqlparser::ast::Statement,
159    ) -> ControlFlow<Self::Break> {
160        if self.options.alphabetize_insert_columns {
161            if let Statement::Insert(Insert {
162                columns,
163                after_columns,
164                source,
165                ..
166            }) = stmt
167            {
168                if let Some(Query { body, .. }) = source.as_deref() {
169                    if let SetExpr::Values(v) = body.deref() {
170                        // `Parens` equality ignores its parenthesis tokens
171                        // (their `PartialEq` is always-equal), so this compares
172                        // the row content alone — matching the sentinel above.
173                        if v.rows
174                            == vec![Parens::with_empty_span(vec![Expr::Value(
175                                Value::Placeholder("...".into()).with_empty_span(),
176                            )])]
177                        {
178                            if columns.len() > 1 {
179                                // `Insert::columns` is now `Vec<ObjectName>`;
180                                // sort by the (unquoted) final identifier part,
181                                // preserving the old `Ident::value` key.
182                                columns.sort_by_key(|s| {
183                                    s.0.last()
184                                        .and_then(|p| p.as_ident())
185                                        .map(|i| i.value.to_lowercase())
186                                        .unwrap_or_default()
187                                });
188                            }
189                            if after_columns.len() > 1 {
190                                after_columns.sort_by_key(|s| s.value.to_lowercase());
191                            }
192                        }
193                    }
194                }
195            }
196        }
197        ControlFlow::Continue(())
198    }
199
200    fn pre_visit_expr(&mut self, expr: &mut Expr) -> ControlFlow<Self::Break> {
201        // A unary op over a literal — directly (`-9`) or through a chain of
202        // unary ops (`- -9`, `+ -9`) — collapses to a *single* placeholder
203        // (`?`, not `-?`). A parenthesised operand (`NOT (TRUE)`) is an
204        // `Expr::Nested`, not a chain, so it isn't collapsed — only its inner
205        // value is, by `pre_visit_value` on descent. Every other literal —
206        // including a plain `Expr::Value` — is normalized by `pre_visit_value`,
207        // so it needs no arm here.
208        if let Expr::UnaryOp { op: _, expr: child } = expr {
209            if Self::is_unary_chain_over_value(child) {
210                *expr = Expr::Value(Value::Placeholder("?".into()).with_empty_span());
211            }
212        }
213        ControlFlow::Continue(())
214    }
215
216    fn pre_visit_value(&mut self, value: &mut ValueWithSpan) -> ControlFlow<Self::Break> {
217        // The base contract: *every* literal `Value` becomes `?`, wherever the
218        // AST holds it. `pre_visit_expr` only catches an `Expr::Value`; a
219        // literal kept in a bare `Value` field — `DATE '…'` / `TIMESTAMP '…'`
220        // (`TypedString`), a `LIKE … ESCAPE '!'` char, a `MATCH … AGAINST '…'`
221        // search string — is reached only through this hook. The visitor now
222        // hands us a `ValueWithSpan`; rewrite the inner `value`, keeping the span.
223        value.value = Value::Placeholder("?".into());
224        ControlFlow::Continue(())
225    }
226
227    fn post_visit_expr(&mut self, expr: &mut Expr) -> ControlFlow<Self::Break> {
228        match expr {
229            Expr::InList { list, .. }
230                if self.options.unify_in_list
231                    && list.iter().all(Self::contains_only_tuples_of_values) =>
232            {
233                *list = vec![Expr::Value(
234                    Value::Placeholder("...".into()).with_empty_span(),
235                )];
236            }
237            _ => {}
238        }
239        ControlFlow::Continue(())
240    }
241}
242
243impl Normalizer {
244    pub fn new() -> Self {
245        Self::default()
246    }
247
248    pub fn with_options(mut self, options: NormalizerOptions) -> Self {
249        self.options = options;
250        self
251    }
252
253    /// Parse and normalize `sql`. [`normalize`] / [`normalize_with_options`]
254    /// are thin free-function wrappers around this.
255    pub fn normalize(
256        dialect: &dyn Dialect,
257        sql: &str,
258        options: NormalizerOptions,
259    ) -> Result<Vec<String>, Error> {
260        let mut statements = Parser::parse_sql(dialect, sql)?;
261        let _ = statements.visit(&mut Self::new().with_options(options));
262        Ok(statements
263            .into_iter()
264            .map(|statement| statement.to_string())
265            .collect::<Vec<String>>())
266    }
267
268    /// Whether `expr` is a literal `Value`, or a chain of unary ops bottoming
269    /// out in one (`-9`, `- -9`, `+ -9`). Such a chain collapses to a single
270    /// `?`; a parenthesised operand (`Expr::Nested`) is *not* a chain, so it
271    /// stops the recursion and its inner value is placeholdered separately.
272    fn is_unary_chain_over_value(expr: &Expr) -> bool {
273        match expr {
274            Expr::Value(_) => true,
275            Expr::UnaryOp { expr: child, .. } => Self::is_unary_chain_over_value(child),
276            _ => false,
277        }
278    }
279
280    /// Check if an expression contains only tuples of constants, recursively.
281    fn contains_only_tuples_of_values(expr: &Expr) -> bool {
282        match expr {
283            Expr::Value(_) => true,
284            Expr::Tuple(v) => v.iter().all(Self::contains_only_tuples_of_values),
285            _ => false,
286        }
287    }
288}
289
290/// Replace a `SELECT TOP 10`-style constant quantity with a `?` placeholder
291/// (rendered `TOP ?`), recursing into set-operation branches. A bare
292/// `TopQuantity::Constant(u64)` isn't a `Value`, so the visitor's literal pass
293/// misses it; `TopQuantity::Expr` is already normalized by that pass.
294fn normalize_top(body: &mut SetExpr) {
295    match body {
296        SetExpr::Select(select) => {
297            if let Some(top) = &mut select.top {
298                if matches!(top.quantity, Some(TopQuantity::Constant(_))) {
299                    top.quantity = Some(TopQuantity::Expr(Expr::Value(
300                        Value::Placeholder("?".into()).with_empty_span(),
301                    )));
302                }
303            }
304        }
305        SetExpr::SetOperation { left, right, .. } => {
306            normalize_top(left);
307            normalize_top(right);
308        }
309        _ => {}
310    }
311}