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::{Query, SetExpr, TopQuantity, Value};
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                    *rows = vec![vec![Expr::Value(
145                        Value::Placeholder("...".into()).with_empty_span(),
146                    )]];
147                }
148            }
149        }
150        ControlFlow::Continue(())
151    }
152
153    fn post_visit_statement(
154        &mut self,
155        stmt: &mut sqlparser::ast::Statement,
156    ) -> ControlFlow<Self::Break> {
157        if self.options.alphabetize_insert_columns {
158            if let Statement::Insert(Insert {
159                columns,
160                after_columns,
161                source,
162                ..
163            }) = stmt
164            {
165                if let Some(Query { body, .. }) = source.as_deref() {
166                    if let SetExpr::Values(v) = body.deref() {
167                        if v.rows
168                            == vec![vec![Expr::Value(
169                                Value::Placeholder("...".into()).with_empty_span(),
170                            )]]
171                        {
172                            if columns.len() > 1 {
173                                columns.sort_by_key(|s| s.value.to_lowercase());
174                            }
175                            if after_columns.len() > 1 {
176                                after_columns.sort_by_key(|s| s.value.to_lowercase());
177                            }
178                        }
179                    }
180                }
181            }
182        }
183        ControlFlow::Continue(())
184    }
185
186    fn pre_visit_expr(&mut self, expr: &mut Expr) -> ControlFlow<Self::Break> {
187        // A unary op over a literal — directly (`-9`) or through a chain of
188        // unary ops (`- -9`, `+ -9`) — collapses to a *single* placeholder
189        // (`?`, not `-?`). A parenthesised operand (`NOT (TRUE)`) is an
190        // `Expr::Nested`, not a chain, so it isn't collapsed — only its inner
191        // value is, by `pre_visit_value` on descent. Every other literal —
192        // including a plain `Expr::Value` — is normalized by `pre_visit_value`,
193        // so it needs no arm here.
194        if let Expr::UnaryOp { op: _, expr: child } = expr {
195            if Self::is_unary_chain_over_value(child) {
196                *expr = Expr::Value(Value::Placeholder("?".into()).with_empty_span());
197            }
198        }
199        ControlFlow::Continue(())
200    }
201
202    fn pre_visit_value(&mut self, value: &mut Value) -> ControlFlow<Self::Break> {
203        // The base contract: *every* literal `Value` becomes `?`, wherever the
204        // AST holds it. `pre_visit_expr` only catches an `Expr::Value`; a
205        // literal kept in a bare `Value` field — `DATE '…'` / `TIMESTAMP '…'`
206        // (`TypedString`), a `LIKE … ESCAPE '!'` char, a `MATCH … AGAINST '…'`
207        // search string — is reached only through this hook.
208        *value = Value::Placeholder("?".into());
209        ControlFlow::Continue(())
210    }
211
212    fn post_visit_expr(&mut self, expr: &mut Expr) -> ControlFlow<Self::Break> {
213        match expr {
214            Expr::InList { list, .. }
215                if self.options.unify_in_list
216                    && list.iter().all(Self::contains_only_tuples_of_values) =>
217            {
218                *list = vec![Expr::Value(
219                    Value::Placeholder("...".into()).with_empty_span(),
220                )];
221            }
222            _ => {}
223        }
224        ControlFlow::Continue(())
225    }
226}
227
228impl Normalizer {
229    pub fn new() -> Self {
230        Self::default()
231    }
232
233    pub fn with_options(mut self, options: NormalizerOptions) -> Self {
234        self.options = options;
235        self
236    }
237
238    /// Parse and normalize `sql`. [`normalize`] / [`normalize_with_options`]
239    /// are thin free-function wrappers around this.
240    pub fn normalize(
241        dialect: &dyn Dialect,
242        sql: &str,
243        options: NormalizerOptions,
244    ) -> Result<Vec<String>, Error> {
245        let mut statements = Parser::parse_sql(dialect, sql)?;
246        let _ = statements.visit(&mut Self::new().with_options(options));
247        Ok(statements
248            .into_iter()
249            .map(|statement| statement.to_string())
250            .collect::<Vec<String>>())
251    }
252
253    /// Whether `expr` is a literal `Value`, or a chain of unary ops bottoming
254    /// out in one (`-9`, `- -9`, `+ -9`). Such a chain collapses to a single
255    /// `?`; a parenthesised operand (`Expr::Nested`) is *not* a chain, so it
256    /// stops the recursion and its inner value is placeholdered separately.
257    fn is_unary_chain_over_value(expr: &Expr) -> bool {
258        match expr {
259            Expr::Value(_) => true,
260            Expr::UnaryOp { expr: child, .. } => Self::is_unary_chain_over_value(child),
261            _ => false,
262        }
263    }
264
265    /// Check if an expression contains only tuples of constants, recursively.
266    fn contains_only_tuples_of_values(expr: &Expr) -> bool {
267        match expr {
268            Expr::Value(_) => true,
269            Expr::Tuple(v) => v.iter().all(Self::contains_only_tuples_of_values),
270            _ => false,
271        }
272    }
273}
274
275/// Replace a `SELECT TOP 10`-style constant quantity with a `?` placeholder
276/// (rendered `TOP ?`), recursing into set-operation branches. A bare
277/// `TopQuantity::Constant(u64)` isn't a `Value`, so the visitor's literal pass
278/// misses it; `TopQuantity::Expr` is already normalized by that pass.
279fn normalize_top(body: &mut SetExpr) {
280    match body {
281        SetExpr::Select(select) => {
282            if let Some(top) = &mut select.top {
283                if matches!(top.quantity, Some(TopQuantity::Constant(_))) {
284                    top.quantity = Some(TopQuantity::Expr(Expr::Value(
285                        Value::Placeholder("?".into()).with_empty_span(),
286                    )));
287                }
288            }
289        }
290        SetExpr::SetOperation { left, right, .. } => {
291            normalize_top(left);
292            normalize_top(right);
293        }
294        _ => {}
295    }
296}