vlorql-llm 0.5.0

Multi-provider LLM client for SQL query generation supporting Anthropic, DeepSeek, Zhipu, and local models
Documentation
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//! Auto Fix Engine: opinionated, safe fixes for [`QueryPlan`](vlorql_core::schema::QueryPlan) AST.
//!
//! This layer runs after the builder and before the validator.  It
//! applies universally safe defaults to fix common issues that small
//! LLMs produce:
//!
//! - **Missing alias** → auto-generate a unique alias for tables
//! - **Limit zero** → remove (default to unlimited)
//! - **Empty select** → inject `[{"type": "star"}]`
//!
//! This layer is **opinionated** — it makes reasonable assumptions so
//! that the validator can focus on real errors.  When in doubt, it
//! does nothing and lets the validator report the issue.

use vlorql_core::schema::{
    Expression, FromClause, InTarget, JoinClause, Predicate, Projection, QueryPlan,
};

/// Run all auto-fix rules on a [`QueryPlan`](vlorql_core::schema::QueryPlan) recursively
/// (including CTE subqueries).
///
/// Returns `true` if any fix was applied.
#[must_use]
pub fn fix_plan(plan: &mut QueryPlan) -> bool {
    let mut changed = false;
    changed |= fix_limit_zero(plan);
    changed |= fix_empty_select(plan);
    changed |= fix_missing_aggregate(plan);
    changed |= fix_missing_group_by(plan);
    // fix_missing_aliases must run last because it adds new aliases.
    changed |= fix_missing_aliases(plan);
    // Replace ORDER BY alias references with the original SELECT expressions.
    changed |= fix_order_by_aliases(plan);
    // Replace WHERE/Having column references that match SELECT aliases.
    changed |= fix_where_alias_refs(plan);
    // Move aggregate conditions from WHERE to HAVING.
    changed |= fix_where_aggregates(plan);
    // Recursively fix CTE subqueries.
    if let Some(ref mut ctes) = plan.ctes {
        for cte in ctes.iter_mut() {
            changed |= fix_plan(&mut cte.query);
        }
    }
    changed
}

/// Remove `LIMIT 0` (set to `None`).
///
/// `LIMIT 0` returns no rows and is almost certainly a mistake from
/// the LLM.  Removing it lets the query proceed normally.
#[must_use]
fn fix_limit_zero(plan: &mut QueryPlan) -> bool {
    if plan.limit == Some(0) {
        plan.limit = None;
        true
    } else {
        false
    }
}

/// Inject a default `[{"type": "star"}]` select when the select list
/// is empty.
///
/// The normalize layer already injects a default select when the
/// field is missing entirely, but the builder may produce an empty
/// vector if all items were invalid.
#[must_use]
fn fix_empty_select(plan: &mut QueryPlan) -> bool {
    if plan.select.is_empty() {
        plan.select = vec![Projection::Star { table: None }];
        true
    } else {
        false
    }
}

/// When `GROUP BY` is present but SELECT has no aggregate function
/// (SUM/COUNT/AVG/MIN/MAX), prepend a suitable aggregate as fallback.
///
/// Small LLMs (7B) often generate `SELECT col GROUP BY col` without
/// any aggregate — valid SQL but meaningless for the user's question.
///
/// Heuristic for choosing the aggregate:
/// - If a non-grouped SELECT column has a numeric-suggesting name
///   (`price`, `total`, `amount`, `quantity`, `cost`, `revenue`, etc.),
///   wrap it with `SUM()`.
/// - Otherwise fall back to `COUNT(*)`.
#[must_use]
fn fix_missing_aggregate(plan: &mut QueryPlan) -> bool {
    // Only applies when GROUP BY is present and non-empty.
    if plan.group_by.as_ref().is_none_or(|g| g.is_empty()) {
        return false;
    }
    // Check if SELECT already has an aggregate function.
    let has_agg = plan.select.iter().any(|p| match p {
        Projection::Expr { expression, .. } => is_aggregate_expr(expression),
        _ => false,
    });
    if has_agg {
        return false;
    }

    // Collect GROUP BY column names (table.column or bare column).
    let group_cols: Vec<(&str, &str)> = plan.group_by.as_ref().map_or_else(Vec::new, |g| {
        g.iter()
            .filter_map(|e| match e {
                Expression::ColumnRef { table, column } => {
                    Some((table.as_deref().unwrap_or(""), column.as_str()))
                }
                _ => None,
            })
            .collect()
    });

    // Find the first non-grouped column with a numeric-suggesting name.
    let agg = plan.select.iter().find_map(|p| match p {
        Projection::Column { table, column, .. } => {
            if group_cols.iter().any(|(t, c)| {
                let t_match = table.as_deref().unwrap_or("") == *t;
                t_match && *c == column.as_str()
            }) {
                return None; // grouped column, skip
            }
            infer_numeric_aggregate(column)
        }
        _ => None,
    });

    match agg {
        Some((name, col)) => {
            // Prepend SUM(col) as the first projection.
            plan.select.insert(
                0,
                Projection::Expr {
                    expression: Expression::FunctionCall {
                        name: name.to_owned(),
                        args: Box::new(vec![Expression::ColumnRef {
                            table: None,
                            column: col.to_owned(),
                        }]),
                        distinct: false,
                    },
                    alias: Some(format!("{}_{}", name, col)),
                },
            );
        }
        None => {
            // Fallback: COUNT(*) as the first projection.
            plan.select.insert(
                0,
                Projection::Expr {
                    expression: Expression::FunctionCall {
                        name: "count".to_owned(),
                        args: Box::new(vec![Expression::Star]),
                        distinct: false,
                    },
                    alias: Some("count".to_owned()),
                },
            );
        }
    }
    true
}

/// Column names that suggest a SUM aggregate is appropriate.
const SUM_COLUMNS: &[&str] = &[
    "price", "total", "amount", "quantity", "cost", "revenue", "salary", "budget", "fee", "rate",
    "score", "value", "count",
];

/// If `column` has a numeric-suggesting name, return `("sum", column)`.
/// Otherwise return `None` (caller falls back to `COUNT(*)`).
fn infer_numeric_aggregate(column: &str) -> Option<(&'static str, &str)> {
    let lower = column.to_lowercase();
    if SUM_COLUMNS.iter().any(|&s| lower.contains(s)) {
        Some(("sum", column))
    } else {
        None
    }
}

/// Returns `true` when `expr` is (or contains) an aggregate function call.
fn is_aggregate_expr(expr: &Expression) -> bool {
    match expr {
        Expression::FunctionCall { name, .. } => vlorql_core::function::is_aggregate(name),
        Expression::BinaryOp { left, right, .. } => {
            is_aggregate_expr(left) || is_aggregate_expr(right)
        }
        _ => false,
    }
}

/// When SELECT has both aggregate functions and bare column references
/// but no GROUP BY, add GROUP BY based on the non-aggregated columns.
///
/// Small LLMs sometimes generate `SELECT name, count(qty) FROM ...`
/// without `GROUP BY name` — valid SQL but semantically wrong for
/// "each/every/per" questions.
#[must_use]
fn fix_missing_group_by(plan: &mut QueryPlan) -> bool {
    // Skip if GROUP BY already exists.
    if plan.group_by.as_ref().is_some_and(|g| !g.is_empty()) {
        return false;
    }
    // Check: SELECT has at least one aggregate AND at least one bare column.
    let has_agg = plan.select.iter().any(|p| match p {
        Projection::Expr { expression, .. } => is_aggregate_expr(expression),
        _ => false,
    });
    if !has_agg {
        return false;
    }
    let bare_cols: Vec<Expression> = plan
        .select
        .iter()
        .filter_map(|p| match p {
            Projection::Column { table, column, .. } => Some(Expression::ColumnRef {
                table: table.clone(),
                column: column.clone(),
            }),
            _ => None,
        })
        .collect();
    if bare_cols.is_empty() {
        return false;
    }
    plan.group_by = Some(bare_cols);
    true
}

/// Auto-generate missing aliases for tables in FROM and JOIN clauses.
///
/// Uses a simple counter-based scheme: `t1`, `t2`, `t3`, etc.
/// Duplicate aliases are avoided by tracking used names.
#[must_use]
fn fix_missing_aliases(plan: &mut QueryPlan) -> bool {
    let mut changed = false;
    let mut alias_counter: u32 = 0;
    let mut used_aliases: Vec<String> = Vec::new();

    // Collect existing aliases.
    collect_existing_aliases(plan, &mut used_aliases);

    // Fix FROM alias.
    changed |= fix_from_alias(plan, &mut alias_counter, &mut used_aliases);

    // Fix JOIN aliases.
    if let Some(joins) = &mut plan.joins {
        for join in joins.iter_mut() {
            changed |= fix_join_alias(join, &mut alias_counter, &mut used_aliases);
        }
    }

    // Fix CTE aliases.
    if let Some(ctes) = &mut plan.ctes {
        for cte in ctes.iter_mut() {
            changed |= fix_missing_aliases(&mut cte.query);
        }
    }

    changed
}

/// Collect all existing aliases from the plan tree.
fn collect_existing_aliases(plan: &QueryPlan, aliases: &mut Vec<String>) {
    if let Some(alias) = plan.from.alias() {
        aliases.push(alias.to_owned());
    }
    if let Some(ref joins) = plan.joins {
        for join in joins {
            if let Some(alias) = join.right_table.alias() {
                aliases.push(alias.to_owned());
            }
        }
    }
    if let Some(ref ctes) = plan.ctes {
        for cte in ctes {
            aliases.push(cte.name.clone());
            collect_existing_aliases(&cte.query, aliases);
        }
    }
}

/// Generate a unique alias name.
fn generate_alias(counter: &mut u32, used: &mut Vec<String>) -> String {
    loop {
        *counter += 1;
        let alias = format!("t{}", counter);
        if !used.contains(&alias) {
            used.push(alias.clone());
            return alias;
        }
    }
}

/// Fix missing alias on FROM clause.
fn fix_from_alias(plan: &mut QueryPlan, counter: &mut u32, used: &mut Vec<String>) -> bool {
    let needs_alias = match &plan.from {
        FromClause::Table { alias, .. } | FromClause::Subquery { alias, .. } => alias.is_none(),
    };
    if needs_alias {
        let alias = generate_alias(counter, used);
        match &mut plan.from {
            FromClause::Table { alias: a, .. } | FromClause::Subquery { alias: a, .. } => {
                *a = Some(alias)
            }
        }
        true
    } else {
        false
    }
}

/// Fix missing alias on a JOIN clause's right_table.
fn fix_join_alias(join: &mut JoinClause, counter: &mut u32, used: &mut Vec<String>) -> bool {
    let needs_alias = match &join.right_table {
        FromClause::Table { alias, .. } | FromClause::Subquery { alias, .. } => alias.is_none(),
    };
    if needs_alias {
        let alias = generate_alias(counter, used);
        match &mut join.right_table {
            FromClause::Table { alias: a, .. } | FromClause::Subquery { alias: a, .. } => {
                *a = Some(alias)
            }
        }
        true
    } else {
        false
    }
}

/// Move aggregate conditions from WHERE to HAVING.
///
/// LLMs frequently put aggregate filter conditions (e.g. `COUNT(*) > 5`) in
/// the WHERE clause instead of HAVING.  This is invalid SQL because aggregate
/// functions cannot appear in WHERE.  This function detects such conditions
/// and moves them to HAVING.
///
/// When WHERE contains any expression with an aggregate function, the entire
/// WHERE predicate is promoted to HAVING (since WHERE cannot contain aggregates,
/// this is safe — the LLM intended these as HAVING conditions).
#[must_use]
fn fix_where_aggregates(plan: &mut QueryPlan) -> bool {
    let Some(ref where_pred) = plan.r#where else {
        return false;
    };

    // Check if WHERE contains any aggregate function call.
    if !contains_aggregate(where_pred) {
        return false;
    }

    // Move the entire WHERE to HAVING.
    // If HAVING already exists, AND the two together.
    let new_having = if let Some(ref having_pred) = plan.having {
        Predicate::And {
            left: Box::new(where_pred.clone()),
            right: Box::new(having_pred.clone()),
        }
    } else {
        where_pred.clone()
    };

    plan.having = Some(new_having);
    plan.r#where = None;
    true
}

/// Recursively check if a predicate tree contains any aggregate function call.
fn contains_aggregate(pred: &Predicate) -> bool {
    match pred {
        Predicate::Comparison { left, right, .. } => {
            is_aggregate_expr(left) || is_aggregate_expr(right)
        }
        Predicate::Between { expr, low, high } => {
            is_aggregate_expr(expr) || is_aggregate_expr(low) || is_aggregate_expr(high)
        }
        Predicate::In { expr, target, .. } => {
            if is_aggregate_expr(expr) {
                return true;
            }
            match target {
                InTarget::Values(values) => values.iter().any(is_aggregate_expr),
                InTarget::SubQuery(_) => false,
            }
        }
        Predicate::Like { expr, .. } => is_aggregate_expr(expr),
        Predicate::IsNull { expr } => is_aggregate_expr(expr),
        Predicate::And { left, right } => contains_aggregate(left) || contains_aggregate(right),
        Predicate::Or { left, right } => contains_aggregate(left) || contains_aggregate(right),
        Predicate::Not { child } => contains_aggregate(child),
        Predicate::Exists { .. } => false,
        Predicate::True | Predicate::False => false,
    }
}

/// Replace ORDER BY expressions that reference SELECT aliases with the
/// original SELECT expression.
///
/// LLMs frequently emit order_by terms that reference an alias from the
/// SELECT list (e.g. `ORDER BY total_amount DESC`), but in the canonical
/// JSON the ORDER BY `expr` must be the actual expression (not an alias).
/// This function builds an alias → expression map from the SELECT list
/// and replaces any ORDER BY `column_ref` that resolves to an alias with
/// the original SELECT expression.
#[must_use]
fn fix_order_by_aliases(plan: &mut QueryPlan) -> bool {
    // Build alias map FIRST (immutable borrow of plan) before accessing order_by.
    let alias_map: Vec<(String, Expression)> = build_alias_map(plan);
    if alias_map.is_empty() {
        return false;
    }

    let Some(ref mut order_by) = plan.order_by else {
        return false;
    };
    if order_by.is_empty() {
        return false;
    }

    let mut changed = false;
    for term in order_by.iter_mut() {
        // Try to find any alias reference in the ORDER BY expression tree.
        if let Some((_, original_expr)) = find_alias_match(&term.expr, &alias_map) {
            term.expr = original_expr.clone();
            changed = true;
        }
    }

    changed
}

/// Build a map of alias → original expression from SELECT projections.
fn build_alias_map(plan: &QueryPlan) -> Vec<(String, Expression)> {
    let mut alias_map = Vec::new();
    for proj in &plan.select {
        match proj {
            Projection::Column {
                column,
                alias: Some(a),
                ..
            } => {
                alias_map.push((
                    a.clone(),
                    Expression::ColumnRef {
                        table: None,
                        column: column.clone(),
                    },
                ));
            }
            Projection::Expr {
                expression,
                alias: Some(a),
                ..
            } => {
                alias_map.push((a.clone(), expression.clone()));
            }
            _ => {}
        }
    }
    alias_map
}

/// Search an expression tree for any ColumnRef that matches a SELECT alias.
/// Returns the (alias_name, original_expression) pair on match.
///
/// This is used by `fix_order_by_aliases` to replace ORDER BY expressions
/// that reference aliases (either directly or inside function wrappers like
/// `sum(total_amount)` or `desc(total_amount)`).  When a match is found,
/// the caller replaces the ENTIRE ORDER BY term expression, avoiding
/// double-wrapping like `sum(sum(orders.total))`.
fn find_alias_match<'a>(
    expr: &Expression,
    alias_map: &'a [(String, Expression)],
) -> Option<&'a (String, Expression)> {
    match expr {
        Expression::ColumnRef { column, .. } => alias_map.iter().find(|(alias, _)| alias == column),
        Expression::FunctionCall { args, .. } => {
            // Check if any arg has a direct alias match.
            for arg in args.iter() {
                if let Some(match_entry) = find_alias_match(arg, alias_map) {
                    return Some(match_entry);
                }
            }
            None
        }
        Expression::BinaryOp { left, right, .. } => {
            find_alias_match(left, alias_map).or_else(|| find_alias_match(right, alias_map))
        }
        _ => None,
    }
}

/// Convenience: create a fix pipeline function that returns a new
/// [`QueryPlan`](vlorql_core::schema::QueryPlan) with all fixes applied.
#[must_use]
pub fn apply_fixes(mut plan: QueryPlan) -> QueryPlan {
    let _ = fix_plan(&mut plan);
    plan
}

/// Replace column references in WHERE/Having predicates that match a SELECT
/// alias with the original expression from the alias.
///
/// Small LLMs frequently reference SELECT aliases (e.g. `orders.total_amount`)
/// in WHERE/ORDER BY clauses as if they were real columns.  This function
/// detects such references and replaces them with the alias's source expression.
#[must_use]
fn fix_where_alias_refs(plan: &mut QueryPlan) -> bool {
    let alias_map = build_alias_map(plan);
    if alias_map.is_empty() || (plan.r#where.is_none() && plan.having.is_none()) {
        return false;
    }

    let mut changed = false;

    if let Some(ref mut predicate) = plan.r#where {
        changed |= replace_alias_in_predicate(predicate, &alias_map);
    }
    if let Some(ref mut predicate) = plan.having {
        changed |= replace_alias_in_predicate(predicate, &alias_map);
    }

    changed
}

/// Recursively walk a predicate tree and replace ColumnRef expressions
/// whose column name matches a SELECT alias with the alias's expression.
fn replace_alias_in_predicate(
    predicate: &mut Predicate,
    alias_map: &[(String, Expression)],
) -> bool {
    let mut changed = false;
    match predicate {
        Predicate::And { left, right } | Predicate::Or { left, right } => {
            changed |= replace_alias_in_predicate(left, alias_map);
            changed |= replace_alias_in_predicate(right, alias_map);
        }
        Predicate::Not { child } => {
            changed |= replace_alias_in_predicate(child, alias_map);
        }
        Predicate::Comparison { left, right, .. } => {
            changed |= replace_alias_in_expression(left, alias_map);
            changed |= replace_alias_in_expression(right, alias_map);
        }
        Predicate::Between { expr, low, high } => {
            changed |= replace_alias_in_expression(expr, alias_map);
            changed |= replace_alias_in_expression(low, alias_map);
            changed |= replace_alias_in_expression(high, alias_map);
        }
        Predicate::In { expr, target } => {
            changed |= replace_alias_in_expression(expr, alias_map);
            if let InTarget::Values(items) = target {
                for item in items.iter_mut() {
                    changed |= replace_alias_in_expression(item, alias_map);
                }
            }
        }
        Predicate::Like { expr, .. } => {
            changed |= replace_alias_in_expression(expr, alias_map);
        }
        Predicate::IsNull { expr } => {
            changed |= replace_alias_in_expression(expr, alias_map);
        }
        Predicate::Exists { query } => {
            changed |= fix_where_alias_refs(query);
        }
        Predicate::True | Predicate::False => {}
    }
    changed
}

/// Recursively walk an expression tree and replace ColumnRef nodes whose
/// column name matches a SELECT alias with the alias's source expression.
fn replace_alias_in_expression(expr: &mut Expression, alias_map: &[(String, Expression)]) -> bool {
    match expr {
        Expression::ColumnRef { column, .. } => {
            if let Some((_, replacement)) = alias_map.iter().find(|(alias, _)| alias == column) {
                *expr = replacement.clone();
                true
            } else {
                false
            }
        }
        Expression::FunctionCall { args, .. } => {
            let mut changed = false;
            for arg in args.iter_mut() {
                changed |= replace_alias_in_expression(arg, alias_map);
            }
            changed
        }
        Expression::BinaryOp { left, right, .. } => {
            let mut changed = false;
            changed |= replace_alias_in_expression(left, alias_map);
            changed |= replace_alias_in_expression(right, alias_map);
            changed
        }
        Expression::Case {
            operand,
            when_thens,
            else_result,
            ..
        } => {
            let mut changed = false;
            if let Some(op) = operand {
                changed |= replace_alias_in_expression(op, alias_map);
            }
            for wt in when_thens.iter_mut() {
                changed |= replace_alias_in_expression(&mut wt.when, alias_map);
                changed |= replace_alias_in_expression(&mut wt.then, alias_map);
            }
            if let Some(el) = else_result {
                changed |= replace_alias_in_expression(el, alias_map);
            }
            changed
        }
        Expression::WindowFunction { args, .. } => {
            let mut changed = false;
            for arg in args.iter_mut() {
                changed |= replace_alias_in_expression(arg, alias_map);
            }
            changed
        }
        Expression::SubQuery { query } => fix_where_alias_refs(query),
        Expression::Literal { .. } => false,
        Expression::Star => false,
    }
}

#[cfg(test)]
mod tests;