vlorql-core 0.5.0

A high-performance SQL query optimizer with constant folding, predicate pushdown, column pruning, and cost-based join reordering
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
//! Fix column references that point to the wrong table via FK relationships.
//!
//! When the LLM writes `order_items.name` but `name` does not exist on
//! `order_items`, this module checks FK relationships to find the correct
//! table.  If `order_items.product_id → products.id` and `products.name`
//! exists, the reference is rewritten to `products.name`.
//!
//! This must run BEFORE `fix_missing_joins` so the rewritten table reference
//! triggers a join to the corrected table.

use crate::schema::{Predicate, Projection, QueryPlan, SchemaSnapshot, expressions::Expression};

/// Try to find `column` on a table related to `table_name` via FK.
///
/// Returns `Some(replacement_table_name)` if found.
fn find_column_via_fk(table_name: &str, column: &str, schema: &SchemaSnapshot) -> Option<String> {
    let table = schema.get_table(table_name)?;
    // Collect all FK columns from this table.
    let fks: Vec<(&str, &str)> = table
        .columns
        .iter()
        .filter_map(|col| {
            col.foreign_key
                .as_ref()
                .map(|fk| (col.name.as_str(), fk.foreign_table.as_str()))
        })
        .collect();
    // For each FK, check if the target table has the desired column.
    for (_local_fk_col, foreign_table) in &fks {
        if let Some(ft) = schema.get_table(foreign_table)
            && ft.columns.iter().any(|c| c.name == column)
        {
            return Some(ft.name.clone());
        }
    }
    // Reverse FK lookup: check if any other table has a FK pointing TO this
    // table AND has the desired column.  This handles LLM mistakes where a
    // column from the FK-referencing table is incorrectly qualified with
    // the FK-target table name (e.g. `users.user_id` instead of `orders.user_id`
    // when `orders.user_id → users.id`).
    for t in &schema.tables {
        for col in &t.columns {
            if let Some(fk) = &col.foreign_key
                && fk.foreign_table == table_name
                && t.columns.iter().any(|c| c.name == column)
            {
                return Some(t.name.clone());
            }
        }
    }
    None
}

/// Recursively fix column references in an expression tree.
fn fix_expr(expr: &mut Expression, schema: &SchemaSnapshot) -> bool {
    match expr {
        Expression::ColumnRef {
            table: Some(table_name),
            column,
        } => {
            // Check if the column actually exists on this table.
            let exists = schema
                .get_table(table_name)
                .is_some_and(|t| t.columns.iter().any(|c| c.name == *column));
            if !exists && let Some(new_table) = find_column_via_fk(table_name, column, schema) {
                *table_name = new_table;
                return true;
            }
            false
        }
        Expression::ColumnRef { .. } => false,
        Expression::FunctionCall { args, .. } => {
            let mut changed = false;
            for arg in args.iter_mut() {
                changed |= fix_expr(arg, schema);
            }
            changed
        }
        Expression::BinaryOp { left, right, .. } => {
            fix_expr(left, schema) | fix_expr(right, schema)
        }
        Expression::Case {
            operand,
            when_thens,
            else_result,
        } => {
            let mut changed = false;
            if let Some(op) = operand {
                changed |= fix_expr(op, schema);
            }
            for wt in when_thens.iter_mut() {
                changed |= fix_expr(&mut wt.when, schema);
                changed |= fix_expr(&mut wt.then, schema);
            }
            if let Some(els) = else_result {
                changed |= fix_expr(els, schema);
            }
            changed
        }
        Expression::SubQuery { query } => fix_plan(query, schema),
        Expression::WindowFunction { args, .. } => {
            let mut changed = false;
            for arg in args.iter_mut() {
                changed |= fix_expr(arg, schema);
            }
            changed
        }
        Expression::Literal { .. } | Expression::Star => false,
    }
}

/// Recursively fix column references in a predicate.
fn fix_pred(pred: &mut Predicate, schema: &SchemaSnapshot) -> bool {
    match pred {
        Predicate::Comparison { left, right, .. } => {
            fix_expr(left, schema) | fix_expr(right, schema)
        }
        Predicate::And { left, right } | Predicate::Or { left, right } => {
            fix_pred(left, schema) | fix_pred(right, schema)
        }
        Predicate::Not { child } => fix_pred(child, schema),
        Predicate::Between { expr, low, high } => {
            fix_expr(expr, schema) | fix_expr(low, schema) | fix_expr(high, schema)
        }
        Predicate::In { expr, target } => {
            let mut changed = fix_expr(expr, schema);
            if let crate::schema::InTarget::SubQuery(query) = target {
                changed |= fix_plan(query, schema);
            }
            changed
        }
        Predicate::Like { expr, .. } => fix_expr(expr, schema),
        Predicate::IsNull { expr } => fix_expr(expr, schema),
        Predicate::Exists { query } => fix_plan(query, schema),
        Predicate::True | Predicate::False => false,
    }
}

/// Recursively fix table references in a whole plan.
fn fix_plan(plan: &mut QueryPlan, schema: &SchemaSnapshot) -> bool {
    let mut changed = false;
    for proj in plan.select.iter_mut() {
        changed |= match proj {
            Projection::Expr { expression, .. } => fix_expr(expression, schema),
            Projection::Column {
                table,
                column,
                alias: _,
            } => {
                if let Some(table_name) = table {
                    let exists = schema
                        .get_table(table_name)
                        .is_some_and(|t| t.columns.iter().any(|c| c.name == *column));
                    if !exists {
                        if let Some(new_table) = find_column_via_fk(table_name, column, schema) {
                            *table_name = new_table;
                            true
                        } else {
                            false
                        }
                    } else {
                        false
                    }
                } else {
                    false
                }
            }
            Projection::Star { .. } => false,
        };
    }
    if let Some(ref mut pred) = plan.r#where {
        changed |= fix_pred(pred, schema);
    }
    if let Some(ref mut having) = plan.having {
        changed |= fix_pred(having, schema);
    }
    if let Some(ref mut group_by) = plan.group_by {
        for expr in group_by.iter_mut() {
            changed |= fix_expr(expr, schema);
        }
        // After fixing table qualifiers, remove any GroupBy expressions that
        // are still qualified ColumnRefs whose column doesn't exist in the
        // schema at all — these are LLM hallucinations (e.g. `orders.category`
        // when `category` is only a SELECT alias, not a real column).
        let before = group_by.len();
        group_by.retain(|expr| {
            if let Expression::ColumnRef {
                table: Some(table_name),
                column,
            } = expr
            {
                let exists = schema
                    .get_table(table_name)
                    .is_some_and(|t| t.columns.iter().any(|c| c.name == *column));
                if exists {
                    return true;
                }
                // Also check reverse FK — maybe the column exists on a
                // related table (redundant with fix_expr above, but keeps
                // the guard self-contained).

                find_column_via_fk(table_name, column, schema).is_some()
            } else {
                true
            }
        });
        if group_by.len() != before {
            changed = true;
        }
    }
    if let Some(ref mut order_by) = plan.order_by {
        for term in order_by.iter_mut() {
            changed |= fix_expr(&mut term.expr, schema);
        }
    }
    if let Some(ref mut joins) = plan.joins {
        for join in joins.iter_mut() {
            changed |= fix_pred(&mut join.on, schema);
        }
    }
    if let Some(ref mut ctes) = plan.ctes {
        for cte in ctes.iter_mut() {
            changed |= fix_plan(&mut cte.query, schema);
        }
    }
    if let Some(ref mut set_op) = plan.set_operation {
        changed |= fix_plan(&mut set_op.right, schema);
    }
    changed
}

/// Fix column references that point to the wrong table via FK lookup.
///
/// When a plan references `order_items.name` but `name` only exists on
/// `products` (reachable via `order_items.product_id → products.id`),
/// rewrites the reference to `products.name`.
pub fn fix_column_table(plan: &mut QueryPlan, schema: &SchemaSnapshot) -> bool {
    fix_plan(plan, schema)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::{
        ColumnSchema, DataType, ForeignKey, FromClause, SchemaMetadata, TableSchema,
    };

    fn test_schema() -> SchemaSnapshot {
        SchemaSnapshot::new(
            vec![
                TableSchema {
                    name: "orders".to_owned(),
                    columns: vec![
                        ColumnSchema {
                            name: "id".to_owned(),
                            data_type: DataType::Int,
                            nullable: false,
                            description: None,
                            is_primary_key: true,
                            foreign_key: None,
                        },
                        ColumnSchema {
                            name: "user_id".to_owned(),
                            data_type: DataType::Int,
                            nullable: false,
                            description: None,
                            is_primary_key: false,
                            foreign_key: Some(ForeignKey {
                                foreign_table: "users".to_owned(),
                                foreign_column: "id".to_owned(),
                            }),
                        },
                    ],
                    description: None,
                    primary_key: Some(vec!["id".to_owned()]),
                },
                TableSchema {
                    name: "users".to_owned(),
                    columns: vec![
                        ColumnSchema {
                            name: "id".to_owned(),
                            data_type: DataType::Int,
                            nullable: false,
                            description: None,
                            is_primary_key: true,
                            foreign_key: None,
                        },
                        ColumnSchema {
                            name: "name".to_owned(),
                            data_type: DataType::String,
                            nullable: false,
                            description: None,
                            is_primary_key: false,
                            foreign_key: None,
                        },
                    ],
                    description: None,
                    primary_key: Some(vec!["id".to_owned()]),
                },
                TableSchema {
                    name: "order_items".to_owned(),
                    columns: vec![
                        ColumnSchema {
                            name: "id".to_owned(),
                            data_type: DataType::Int,
                            nullable: false,
                            description: None,
                            is_primary_key: true,
                            foreign_key: None,
                        },
                        ColumnSchema {
                            name: "order_id".to_owned(),
                            data_type: DataType::Int,
                            nullable: false,
                            description: None,
                            is_primary_key: false,
                            foreign_key: Some(ForeignKey {
                                foreign_table: "orders".to_owned(),
                                foreign_column: "id".to_owned(),
                            }),
                        },
                        ColumnSchema {
                            name: "product_id".to_owned(),
                            data_type: DataType::Int,
                            nullable: false,
                            description: None,
                            is_primary_key: false,
                            foreign_key: Some(ForeignKey {
                                foreign_table: "products".to_owned(),
                                foreign_column: "id".to_owned(),
                            }),
                        },
                        ColumnSchema {
                            name: "quantity".to_owned(),
                            data_type: DataType::Int,
                            nullable: false,
                            description: None,
                            is_primary_key: false,
                            foreign_key: None,
                        },
                    ],
                    description: None,
                    primary_key: Some(vec!["id".to_owned()]),
                },
                TableSchema {
                    name: "products".to_owned(),
                    columns: vec![
                        ColumnSchema {
                            name: "id".to_owned(),
                            data_type: DataType::Int,
                            nullable: false,
                            description: None,
                            is_primary_key: true,
                            foreign_key: None,
                        },
                        ColumnSchema {
                            name: "name".to_owned(),
                            data_type: DataType::String,
                            nullable: false,
                            description: None,
                            is_primary_key: false,
                            foreign_key: None,
                        },
                    ],
                    description: None,
                    primary_key: Some(vec!["id".to_owned()]),
                },
            ],
            SchemaMetadata {
                version: Some("1.0".to_owned()),
                source: Some("test".to_owned()),
                generated_at: None,
            },
        )
    }

    #[test]
    fn fixes_order_items_name_to_products_name() {
        let schema = test_schema();
        let mut plan = QueryPlan {
            select: vec![
                Projection::Column {
                    table: Some("orders".to_owned()),
                    column: "id".to_owned(),
                    alias: None,
                },
                Projection::Expr {
                    expression: Expression::FunctionCall {
                        name: "string_agg".to_owned(),
                        args: Box::new(vec![Expression::ColumnRef {
                            table: Some("order_items".to_owned()),
                            column: "name".to_owned(),
                        }]),
                        distinct: false,
                    },
                    alias: Some("product_names".to_owned()),
                },
            ],
            distinct: false,
            distinct_on: None,
            from: FromClause::table("orders".to_owned(), None),
            r#where: None,
            group_by: None,
            having: None,
            order_by: None,
            limit: None,
            offset: None,
            joins: None,
            ctes: None,
            set_operation: None,
        };

        assert!(fix_column_table(&mut plan, &schema));

        // The string_agg arg should now reference products.name
        if let Projection::Expr { expression, .. } = &plan.select[1] {
            if let Expression::FunctionCall { args, .. } = expression {
                assert_eq!(args.len(), 1);
                match &args[0] {
                    Expression::ColumnRef {
                        table: Some(t),
                        column: c,
                    } => {
                        assert_eq!(t, "products");
                        assert_eq!(c, "name");
                    }
                    _ => panic!("expected ColumnRef after fix"),
                }
            } else {
                panic!("expected FunctionCall");
            }
        } else {
            panic!("expected Expr projection");
        }
    }

    #[test]
    fn leaves_valid_column_refs_unchanged() {
        let schema = test_schema();
        let mut plan = QueryPlan {
            select: vec![Projection::Column {
                table: Some("orders".to_owned()),
                column: "id".to_owned(),
                alias: None,
            }],
            distinct: false,
            distinct_on: None,
            from: FromClause::table("orders".to_owned(), None),
            r#where: None,
            group_by: None,
            having: None,
            order_by: None,
            limit: None,
            offset: None,
            joins: None,
            ctes: None,
            set_operation: None,
        };

        assert!(!fix_column_table(&mut plan, &schema));
    }

    #[test]
    fn no_change_when_column_not_found_anywhere() {
        let schema = test_schema();
        let mut plan = QueryPlan {
            select: vec![Projection::Column {
                table: Some("order_items".to_owned()),
                column: "nonexistent".to_owned(),
                alias: None,
            }],
            distinct: false,
            distinct_on: None,
            from: FromClause::table("orders".to_owned(), None),
            r#where: None,
            group_by: None,
            having: None,
            order_by: None,
            limit: None,
            offset: None,
            joins: None,
            ctes: None,
            set_operation: None,
        };

        assert!(!fix_column_table(&mut plan, &schema));
    }
}