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
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
//! Schema existence validation for query plans.

use crate::errors::{SchemaErrorKind, VlorQLError};
use crate::function::{is_known_function, lookup_function};
use crate::query::{ColumnReference, QueryScope, collect_plan_references};
use crate::schema::{
    Expression, FromClause, InTarget, JoinType, Predicate, Projection, QueryPlan, SchemaSnapshot,
};
use serde_json::json;
use std::collections::HashSet;
use tracing::debug;

/// Checks every base table and column reference against a schema snapshot.
pub fn validate_schema(plan: &QueryPlan, schema: &SchemaSnapshot) -> Result<(), Vec<VlorQLError>> {
    let mut errors = Vec::new();
    validate_plan(plan, schema, &mut errors);
    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

fn validate_plan(plan: &QueryPlan, schema: &SchemaSnapshot, errors: &mut Vec<VlorQLError>) {
    validate_plan_with_outer(plan, schema, errors, None);
}

fn validate_plan_with_outer(
    plan: &QueryPlan,
    schema: &SchemaSnapshot,
    errors: &mut Vec<VlorQLError>,
    outer_scope: Option<&QueryScope>,
) {
    // DISTINCT + GROUP BY: MySQL allows it (DISTINCT is applied after
    // aggregation), so we only warn rather than reject.
    if plan.distinct
        && plan.group_by.is_some()
        && plan.group_by.as_ref().is_some_and(|g| !g.is_empty())
    {
        tracing::warn!(
            "DISTINCT and GROUP BY used together: DISTINCT is applied after aggregation. \
             This is valid in MySQL but may be semantically ambiguous in other dialects. \
             distinct=true group_by={:?}",
            plan.group_by,
        );
    }

    // SELECT * combined with GROUP BY: star-expanded columns may not all
    // be in the GROUP BY clause, producing invalid SQL in most dialects.
    if plan.group_by.is_some()
        && plan.group_by.as_ref().is_some_and(|g| !g.is_empty())
        && plan
            .select
            .iter()
            .any(|p| matches!(p, Projection::Star { .. }))
    {
        errors.push(VlorQLError::validation(
            crate::errors::ValidationErrorKind::AggregationMismatch {
                message: "SELECT * with GROUP BY may include columns that are not \
                          in the GROUP BY clause; consider listing columns explicitly"
                    .to_owned(),
            },
            serde_json::json!({"select": plan.select, "group_by": plan.group_by}),
        ));
    }

    if let Some(ctes) = &plan.ctes {
        for cte in ctes {
            validate_plan_with_outer(&cte.query, schema, errors, None);
        }
    }

    // Validate subquery in FROM clause.
    if let FromClause::Subquery { query, .. } = &plan.from {
        validate_plan_with_outer(query, schema, errors, None);
    }

    // Validate subquery in JOIN right tables.
    if let Some(joins) = &plan.joins {
        for join in joins {
            if let FromClause::Subquery { query, .. } = &join.right_table {
                validate_plan_with_outer(query, schema, errors, None);
            }
        }
    }

    let mut scope = QueryScope::from_plan(plan);
    if let Some(outer) = outer_scope {
        debug!(
            "extending scope with outer: {:?}",
            outer.sources.iter().map(|s| &s.table).collect::<Vec<_>>()
        );
        scope.extend_with_outer(outer);
    }
    let mut reported_tables = HashSet::new();
    let mut reported_columns = HashSet::new();

    for source in &scope.sources {
        if !scope.cte_names.contains(&source.table)
            && schema.get_table(&source.table).is_none()
            && reported_tables.insert(source.table.clone())
        {
            errors.push(table_not_found_error(&source.table, schema));
        }
    }

    let references = collect_plan_references(plan);
    for qualifier in references.stars.into_iter().flatten() {
        if scope.resolve_source(&qualifier).is_none() && reported_tables.insert(qualifier.clone()) {
            errors.push(table_not_in_scope_or_not_found(&qualifier, schema));
        }
    }

    for reference in references.columns {
        validate_column_reference(
            &reference,
            &scope,
            schema,
            errors,
            &mut reported_tables,
            &mut reported_columns,
        );
    }

    validate_subqueries_in_plan(plan, schema, errors, &scope);
}

fn validate_column_reference(
    reference: &ColumnReference,
    scope: &QueryScope,
    schema: &SchemaSnapshot,
    errors: &mut Vec<VlorQLError>,
    reported_tables: &mut HashSet<String>,
    reported_columns: &mut HashSet<(String, String)>,
) {
    if let Some(qualifier) = &reference.table {
        let Some(source) = scope.resolve_source(qualifier) else {
            if reported_tables.insert(qualifier.clone()) {
                errors.push(table_not_in_scope_or_not_found(qualifier, schema));
            }
            return;
        };
        if scope.cte_names.contains(&source.table) {
            return;
        }
        let Some(table) = schema.get_table(&source.table) else {
            return;
        };
        if !table
            .columns
            .iter()
            .any(|column| column.name == reference.column)
        {
            push_column_not_found(
                &table.name,
                &reference.column,
                schema,
                errors,
                reported_columns,
            );
        }
        return;
    }

    let found = scope
        .sources
        .iter()
        .filter(|source| !scope.cte_names.contains(&source.table))
        .filter_map(|source| schema.get_table(&source.table))
        .any(|table| {
            table
                .columns
                .iter()
                .any(|column| column.name == reference.column)
        });
    if found
        || scope
            .sources
            .iter()
            .any(|source| scope.cte_names.contains(&source.table))
    {
        return;
    }

    let table = scope
        .sources
        .first()
        .map_or("<unknown>", |source| source.table.as_str());
    push_column_not_found(table, &reference.column, schema, errors, reported_columns);
}

fn push_column_not_found(
    table: &str,
    column: &str,
    schema: &SchemaSnapshot,
    errors: &mut Vec<VlorQLError>,
    reported_columns: &mut HashSet<(String, String)>,
) {
    if !reported_columns.insert((table.to_owned(), column.to_owned())) {
        return;
    }
    let available_columns = schema
        .get_table(table)
        .map(|table| {
            table
                .columns
                .iter()
                .map(|candidate| candidate.name.as_str())
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    errors.push(VlorQLError::schema(
        SchemaErrorKind::ColumnNotFound {
            table: table.to_owned(),
            column: column.to_owned(),
        },
        json!({
            "table": table,
            "column": column,
            "available_columns": available_columns,
        }),
    ));
}

/// Returns a `TableNotInScope` error when `table` exists in the schema,
/// or a `TableNotFound` error when `table` is genuinely missing.
fn table_not_in_scope_or_not_found(table: &str, schema: &SchemaSnapshot) -> VlorQLError {
    debug!("table_not_in_scope_or_not_found: {}", table);
    let context = json!({
        "table": table,
        "available_tables": schema
            .tables
            .iter()
            .map(|candidate| candidate.name.as_str())
            .collect::<Vec<_>>(),
    });
    if schema.get_table(table).is_some() {
        VlorQLError::schema(
            SchemaErrorKind::TableNotInScope {
                table: table.to_owned(),
            },
            context,
        )
    } else {
        VlorQLError::schema(
            SchemaErrorKind::TableNotFound {
                table: table.to_owned(),
            },
            context,
        )
    }
}

/// Recursively validate subqueries found in predicates and expressions.
fn validate_subqueries_in_plan(
    plan: &QueryPlan,
    schema: &SchemaSnapshot,
    errors: &mut Vec<VlorQLError>,
    outer_scope: &QueryScope,
) {
    for projection in &plan.select {
        if let Projection::Expr { expression, .. } = projection {
            validate_subqueries_in_expression(expression, schema, errors, outer_scope);
        }
    }
    if let Some(predicate) = &plan.r#where {
        validate_subqueries_in_predicate(predicate, schema, errors, outer_scope);
    }
    if let Some(expressions) = &plan.group_by {
        for expression in expressions {
            validate_subqueries_in_expression(expression, schema, errors, outer_scope);
        }
    }
    if let Some(predicate) = &plan.having {
        validate_subqueries_in_predicate(predicate, schema, errors, outer_scope);
    }
    if let Some(terms) = &plan.order_by {
        for term in terms {
            validate_subqueries_in_expression(&term.expr, schema, errors, outer_scope);
        }
    }
    if let Some(joins) = &plan.joins {
        for join in joins {
            // CROSS JOIN's ON condition is ignored by the compiler; don't
            // validate subqueries inside it either (keeps validation and
            // compilation consistent).
            if join.join_type != JoinType::Cross {
                validate_subqueries_in_predicate(&join.on, schema, errors, outer_scope);
            }
        }
    }
}

fn validate_subqueries_in_expression(
    expression: &Expression,
    schema: &SchemaSnapshot,
    errors: &mut Vec<VlorQLError>,
    outer_scope: &QueryScope,
) {
    match expression {
        Expression::SubQuery { query } => {
            validate_plan_with_outer(query, schema, errors, Some(outer_scope));
        }
        Expression::FunctionCall { name, args, .. } => {
            if !is_known_function(name) {
                tracing::warn!("Unknown function '{}' in query plan", name);
            } else if let Some(def) = lookup_function(name) {
                if (args.len()) < def.min_args {
                    errors.push(VlorQLError::validation(
                        crate::errors::ValidationErrorKind::AggregationMismatch {
                            message: format!(
                                "Function '{}' requires at least {} arguments, got {}",
                                name,
                                def.min_args,
                                args.len()
                            ),
                        },
                        serde_json::json!({"function": name, "min_args": def.min_args, "actual": args.len()}),
                    ));
                }
                if let Some(max) = def.max_args
                    && (args.len()) > max
                {
                    errors.push(VlorQLError::validation(
                        crate::errors::ValidationErrorKind::AggregationMismatch {
                            message: format!(
                                "Function '{}' accepts at most {} arguments, got {}",
                                name,
                                max,
                                args.len()
                            ),
                        },
                        serde_json::json!({"function": name, "max_args": max, "actual": args.len()}),
                    ));
                }
            }
            for argument in args.iter() {
                validate_subqueries_in_expression(argument, schema, errors, outer_scope);
            }
        }
        Expression::BinaryOp { left, right, .. } => {
            validate_subqueries_in_expression(left, schema, errors, outer_scope);
            validate_subqueries_in_expression(right, schema, errors, outer_scope);
        }
        _ => {}
    }
}

fn validate_subqueries_in_predicate(
    predicate: &Predicate,
    schema: &SchemaSnapshot,
    errors: &mut Vec<VlorQLError>,
    outer_scope: &QueryScope,
) {
    match predicate {
        Predicate::Comparison { left, right, .. } => {
            validate_subqueries_in_expression(left, schema, errors, outer_scope);
            validate_subqueries_in_expression(right, schema, errors, outer_scope);
        }
        Predicate::And { left, right } | Predicate::Or { left, right } => {
            validate_subqueries_in_predicate(left, schema, errors, outer_scope);
            validate_subqueries_in_predicate(right, schema, errors, outer_scope);
        }
        Predicate::Not { child } => {
            validate_subqueries_in_predicate(child, schema, errors, outer_scope);
        }
        Predicate::Between { expr, low, high } => {
            validate_subqueries_in_expression(expr, schema, errors, outer_scope);
            validate_subqueries_in_expression(low, schema, errors, outer_scope);
            validate_subqueries_in_expression(high, schema, errors, outer_scope);
        }
        Predicate::In { expr, target } => {
            validate_subqueries_in_expression(expr, schema, errors, outer_scope);
            if let InTarget::SubQuery(query) = target {
                validate_plan_with_outer(query, schema, errors, Some(outer_scope));
            }
        }
        Predicate::Exists { query } => {
            validate_plan_with_outer(query, schema, errors, Some(outer_scope));
        }
        Predicate::Like { expr, .. } | Predicate::IsNull { expr } => {
            validate_subqueries_in_expression(expr, schema, errors, outer_scope);
        }
        Predicate::True | Predicate::False => {}
    }
}

fn table_not_found_error(table: &str, schema: &SchemaSnapshot) -> VlorQLError {
    VlorQLError::schema(
        SchemaErrorKind::TableNotFound {
            table: table.to_owned(),
        },
        json!({
            "table": table,
            "available_tables": schema
                .tables
                .iter()
                .map(|candidate| candidate.name.as_str())
                .collect::<Vec<_>>(),
        }),
    )
}

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

    fn column(name: &str) -> ColumnSchema {
        ColumnSchema {
            name: name.to_owned(),
            data_type: DataType::Int,
            nullable: false,
            description: None,
            is_primary_key: false,
            foreign_key: None,
        }
    }

    fn two_table_schema() -> SchemaSnapshot {
        SchemaSnapshot::new(
            vec![
                TableSchema {
                    name: "users".to_owned(),
                    columns: vec![column("id"), column("name")],
                    description: None,
                    primary_key: Some(vec!["id".to_owned()]),
                },
                TableSchema {
                    name: "products".to_owned(),
                    columns: vec![column("id"), column("name")],
                    description: None,
                    primary_key: Some(vec!["id".to_owned()]),
                },
            ],
            SchemaMetadata::default(),
        )
    }

    /// A CROSS JOIN whose `on` references a hallucinated column must still
    /// pass schema validation: the compiler ignores the condition, so the
    /// validator must not flag columns inside it.
    #[test]
    fn cross_join_with_bogus_on_condition_passes_validation() {
        let schema = two_table_schema();
        let plan = QueryPlan {
            select: vec![
                Projection::Column {
                    table: Some("users".to_owned()),
                    column: "name".to_owned(),
                    alias: None,
                },
                Projection::Column {
                    table: Some("products".to_owned()),
                    column: "name".to_owned(),
                    alias: None,
                },
            ],
            distinct: false,
            distinct_on: None,
            from: FromClause::table("users".to_owned(), None),
            r#where: None,
            group_by: None,
            having: None,
            order_by: None,
            limit: None,
            offset: None,
            joins: Some(vec![JoinClause {
                join_type: JoinType::Cross,
                right_table: FromClause::table("products".to_owned(), None),
                // Hallucinated `users.product_id` — invalid, but must be ignored.
                on: Predicate::Comparison {
                    left: Box::new(Expression::ColumnRef {
                        table: Some("products".to_owned()),
                        column: "id".to_owned(),
                    }),
                    op: ComparisonOperator::Eq,
                    right: Box::new(Expression::ColumnRef {
                        table: Some("users".to_owned()),
                        column: "product_id".to_owned(),
                    }),
                },
            }]),
            ctes: None,
            set_operation: None,
        };

        assert!(validate_schema(&plan, &schema).is_ok());
    }

    /// A non-CROSS join's `on` is still validated: a hallucinated column fails.
    #[test]
    fn inner_join_with_bogus_on_condition_fails_validation() {
        let schema = two_table_schema();
        let plan = QueryPlan {
            select: vec![Projection::Column {
                table: Some("users".to_owned()),
                column: "name".to_owned(),
                alias: None,
            }],
            distinct: false,
            distinct_on: None,
            from: FromClause::table("users".to_owned(), None),
            r#where: None,
            group_by: None,
            having: None,
            order_by: None,
            limit: None,
            offset: None,
            joins: Some(vec![JoinClause {
                join_type: JoinType::Inner,
                right_table: FromClause::table("products".to_owned(), None),
                on: Predicate::Comparison {
                    left: Box::new(Expression::ColumnRef {
                        table: Some("products".to_owned()),
                        column: "id".to_owned(),
                    }),
                    op: ComparisonOperator::Eq,
                    right: Box::new(Expression::ColumnRef {
                        table: Some("users".to_owned()),
                        column: "product_id".to_owned(),
                    }),
                },
            }]),
            ctes: None,
            set_operation: None,
        };

        assert!(validate_schema(&plan, &schema).is_err());
    }
}