1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//! Schema-aware AST fixer that repairs common LLM mistakes before validation.
//!
//! These fixes are applied AFTER the builder produces a [`QueryPlan`] and BEFORE
//! [`validate::ValidationPipeline`] checks it. Because they use the real schema
//! to look up tables, columns, and foreign-key relationships, they are more
//! reliable than heuristic JSON-level normalisation.
pub
use crate;
use debug;
/// Apply schema-aware fixes to `plan`.
///
/// Returns `true` if any change was made.
///
/// # Fixes applied (in order)
///
/// 0. **Arithmetic column refs** — column names like `"unit_price * quantity"`
/// are converted from a malformed `ColumnRef` into a proper `BinaryOp` tree.
/// 1. **Wrong-table column refs** — `order_items.name` rewritten to
/// `products.name` when `name` only exists on a FK-related table.
/// 2. **Missing joins** — tables referenced in SELECT/WHERE that are not in
/// FROM/JOINS get the correct INNER JOIN added, using the schema's actual
/// foreign-key metadata.
/// 3. **Nested aggregate dedup** — `SUM(SUM(x))` / `COUNT(COUNT(x))` unwrapped
/// to a single function call.
/// 4. **GROUP BY repair** — literal-null entries removed, non-aggregated
/// SELECT columns added.