vlorql 0.5.0

High-level SQL query optimization and LLM-powered natural language querying library
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
//! Dialect-feature bypass attempts.
//!
//! These tests verify that [`DialectProfile`] constraints (CTE, JOIN
//! count, OFFSET, allowed functions, allowed join types) cannot be
//! sidestepped by a hostile LLM.
//!
//! Every plan is validated through [`DialectValidator::validate`]
//! and is expected to surface a [`VlorQLError::Validation`] error of
//! the corresponding kind.

use std::sync::Arc;

use vlorql_core::errors::{ValidationErrorKind, VlorQLError};
use vlorql_core::schema::{
    ColumnSchema, ComparisonOperator, DataType, DialectProfile, Expression, FromClause,
    IdentifierQuoting, JoinClause, JoinType, Predicate, Projection, QueryPlan, SchemaMetadata,
    SqlDialect, TableSchema,
};
use vlorql_core::validate::dialect::DialectValidator;

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

fn base_plan() -> QueryPlan {
    QueryPlan {
        select: vec![Projection::Column {
            table: Some("users".to_owned()),
            column: "id".to_owned(),
            alias: None,
        }],
        from: FromClause::table("users".to_owned(), None),
        r#where: None,
        group_by: None,
        having: None,
        order_by: None,
        limit: None,
        offset: None,
        joins: None,
        ctes: None,
        distinct: false,
        distinct_on: None,
        set_operation: None,
    }
}

fn restricted_profile() -> DialectProfile {
    DialectProfile {
        dialect: SqlDialect::Sqlite,
        quote_style: IdentifierQuoting::DoubleQuote,
        supports_cte: false,
        supports_window_functions: false,
        supports_json_operations: false,
        max_joins: Some(2),
        allowed_join_types: vec![JoinType::Inner],
        allowed_functions: vec!["count".to_owned()],
        denied_functions: vec!["load_extension".to_owned()],
        max_group_by_columns: Some(2),
        allow_distinct: false,
        allow_select_distinct: false,
        supports_offset: false,
        supports_fetch: false,
    }
}

fn assert_validation_error(
    errors: &[VlorQLError],
    predicate: impl Fn(&ValidationErrorKind) -> bool,
) {
    assert!(
        errors.iter().any(|error| matches!(
            error,
            VlorQLError::Validation { kind, .. } if predicate(kind)
        )),
        "no matching validation error in: {errors:#?}"
    );
}

// ---------------------------------------------------------------------
// 1. CTE
// ---------------------------------------------------------------------

#[test]
fn cte_is_rejected_when_profile_disables_it() {
    let mut plan = base_plan();
    plan.ctes = Some(vec![vlorql_core::schema::CommonTableExpression {
        name: "active_users".to_owned(),
        recursive: false,
        query: Box::new(base_plan()),
    }]);
    let errors = DialectValidator::validate(&plan, &restricted_profile())
        .expect_err("CTE should be rejected");
    assert_validation_error(
        &errors,
        |kind| matches!(kind, ValidationErrorKind::DialectFeatureDisabled { feature } if feature == "common_table_expressions"),
    );
}

#[test]
fn cte_in_nested_query_is_rejected_recursively() {
    // The hostile plan hides a CTE inside another CTE's body. The
    // dialect validator must recurse into every CTE so the inner one
    // is also caught by the `supports_cte = false` profile.
    let inner_cte = vlorql_core::schema::CommonTableExpression {
        name: "staging".to_owned(),
        recursive: false,
        query: Box::new(QueryPlan {
            ctes: Some(vec![vlorql_core::schema::CommonTableExpression {
                name: "inner_staging".to_owned(),
                recursive: false,
                query: Box::new(base_plan()),
            }]),
            ..base_plan()
        }),
    };
    let mut outer = base_plan();
    outer.ctes = Some(vec![inner_cte]);
    let errors = DialectValidator::validate(&outer, &restricted_profile())
        .expect_err("nested CTE must be rejected by recursive validation");
    // Both the outer and the inner CTE should be flagged.
    let feature_errors: Vec<_> = errors
        .iter()
        .filter_map(|error| match error {
            VlorQLError::Validation {
                kind: ValidationErrorKind::DialectFeatureDisabled { feature },
                ..
            } => Some(feature.clone()),
            _ => None,
        })
        .collect();
    assert!(
        feature_errors
            .iter()
            .all(|feature| feature == "common_table_expressions"),
        "expected only CTE feature errors, got {feature_errors:?}"
    );
    assert!(
        feature_errors.len() >= 2,
        "expected at least two CTE errors (outer + nested), got {feature_errors:?}"
    );
}

// ---------------------------------------------------------------------
// 2. JOIN count
// ---------------------------------------------------------------------

#[test]
fn too_many_joins_is_rejected() {
    let mut plan = base_plan();
    plan.joins = Some(vec![
        JoinClause {
            join_type: JoinType::Inner,
            right_table: FromClause::table("users".to_owned(), Some("u2".to_owned())),
            on: Predicate::Comparison {
                left: Box::new(Expression::ColumnRef {
                    table: Some("users".to_owned()),
                    column: "id".to_owned(),
                }),
                op: ComparisonOperator::Eq,
                right: Box::new(Expression::ColumnRef {
                    table: Some("u2".to_owned()),
                    column: "id".to_owned(),
                }),
            },
        },
        JoinClause {
            join_type: JoinType::Inner,
            right_table: FromClause::table("users".to_owned(), Some("u3".to_owned())),
            on: Predicate::Comparison {
                left: Box::new(Expression::ColumnRef {
                    table: Some("users".to_owned()),
                    column: "id".to_owned(),
                }),
                op: ComparisonOperator::Eq,
                right: Box::new(Expression::ColumnRef {
                    table: Some("u3".to_owned()),
                    column: "id".to_owned(),
                }),
            },
        },
        JoinClause {
            join_type: JoinType::Inner,
            right_table: FromClause::table("users".to_owned(), Some("u4".to_owned())),
            on: Predicate::Comparison {
                left: Box::new(Expression::ColumnRef {
                    table: Some("users".to_owned()),
                    column: "id".to_owned(),
                }),
                op: ComparisonOperator::Eq,
                right: Box::new(Expression::ColumnRef {
                    table: Some("u4".to_owned()),
                    column: "id".to_owned(),
                }),
            },
        },
    ]);
    // restricted_profile caps at 2 joins.
    let errors = DialectValidator::validate(&plan, &restricted_profile())
        .expect_err("three joins should be rejected");
    assert_validation_error(&errors, |kind| {
        matches!(
            kind,
            ValidationErrorKind::TooManyJoins { actual: 3, max: 2 }
        )
    });
}

#[test]
fn disallowed_join_type_is_rejected() {
    let mut plan = base_plan();
    plan.joins = Some(vec![JoinClause {
        join_type: JoinType::Right,
        right_table: FromClause::table("users".to_owned(), Some("u2".to_owned())),
        on: Predicate::Comparison {
            left: Box::new(Expression::ColumnRef {
                table: Some("users".to_owned()),
                column: "id".to_owned(),
            }),
            op: ComparisonOperator::Eq,
            right: Box::new(Expression::ColumnRef {
                table: Some("u2".to_owned()),
                column: "id".to_owned(),
            }),
        },
    }]);
    let errors = DialectValidator::validate(&plan, &restricted_profile())
        .expect_err("RIGHT JOIN must be rejected");
    assert_validation_error(
        &errors,
        |kind| matches!(kind, ValidationErrorKind::DialectFeatureDisabled { feature } if feature.contains("right")),
    );
}

// ---------------------------------------------------------------------
// 3. OFFSET
// ---------------------------------------------------------------------

#[test]
fn offset_is_rejected_when_profile_disables_it() {
    let mut plan = base_plan();
    plan.offset = Some(10);
    let errors = DialectValidator::validate(&plan, &restricted_profile())
        .expect_err("offset must be rejected when supports_offset = false");
    assert_validation_error(
        &errors,
        |kind| matches!(kind, ValidationErrorKind::DialectFeatureDisabled { feature } if feature == "offset"),
    );
}

#[test]
fn offset_inside_a_cte_is_rejected() {
    // The hostile plan hides the offset inside a CTE. Dialect features
    // must be enforced recursively so the offset is still flagged.
    let mut cte_inner = base_plan();
    cte_inner.offset = Some(5);
    let mut plan = base_plan();
    plan.ctes = Some(vec![vlorql_core::schema::CommonTableExpression {
        name: "paged".to_owned(),
        recursive: false,
        query: Box::new(cte_inner),
    }]);
    // For this test we still need a CTE-enabled profile, otherwise the
    // CTE itself is rejected and we never reach the offset check.
    let mut profile = restricted_profile();
    profile.supports_cte = true;
    profile.supports_offset = false;
    let errors = DialectValidator::validate(&plan, &profile).expect_err("offset should fail");
    assert_validation_error(
        &errors,
        |kind| matches!(kind, ValidationErrorKind::DialectFeatureDisabled { feature } if feature == "offset"),
    );
}

// ---------------------------------------------------------------------
// 4. Functions
// ---------------------------------------------------------------------

#[test]
fn function_not_in_allowlist_is_rejected() {
    let mut plan = base_plan();
    plan.select = vec![Projection::Expr {
        expression: Expression::FunctionCall {
            name: "sum".to_owned(),
            args: Box::new(vec![Expression::ColumnRef {
                table: Some("users".to_owned()),
                column: "id".to_owned(),
            }]),
            distinct: false,
        },
        alias: None,
    }];
    let errors = DialectValidator::validate(&plan, &restricted_profile())
        .expect_err("`sum` is not in the allowlist and must be rejected");
    assert_validation_error(
        &errors,
        |kind| matches!(kind, ValidationErrorKind::InvalidFunction { function, .. } if function == "sum"),
    );
}

#[test]
fn explicitly_denied_function_is_rejected() {
    let mut plan = base_plan();
    plan.select = vec![Projection::Expr {
        expression: Expression::FunctionCall {
            name: "load_extension".to_owned(),
            args: Box::new(vec![Expression::Literal {
                value: serde_json::Value::String("/tmp/evil.so".to_owned()),
                data_type: DataType::String,
            }]),
            distinct: false,
        },
        alias: None,
    }];
    let errors = DialectValidator::validate(&plan, &restricted_profile())
        .expect_err("load_extension must always be rejected");
    assert_validation_error(
        &errors,
        |kind| matches!(kind, ValidationErrorKind::InvalidFunction { function, .. } if function == "load_extension"),
    );
}

#[test]
fn distinct_keyword_is_rejected_when_disallowed() {
    let mut plan = base_plan();
    plan.select = vec![Projection::Expr {
        expression: Expression::FunctionCall {
            name: "count".to_owned(),
            args: Box::new(vec![Expression::ColumnRef {
                table: Some("users".to_owned()),
                column: "id".to_owned(),
            }]),
            distinct: true,
        },
        alias: None,
    }];
    let errors = DialectValidator::validate(&plan, &restricted_profile())
        .expect_err("DISTINCT must be rejected when allow_distinct = false");
    assert_validation_error(
        &errors,
        |kind| matches!(kind, ValidationErrorKind::DialectFeatureDisabled { feature } if feature == "distinct"),
    );
}

// ---------------------------------------------------------------------
// 5. GROUP BY limit
// ---------------------------------------------------------------------

#[test]
fn too_many_group_by_columns_is_rejected() {
    let mut plan = base_plan();
    plan.group_by = Some(vec![
        Expression::ColumnRef {
            table: Some("users".to_owned()),
            column: "id".to_owned(),
        },
        Expression::ColumnRef {
            table: Some("users".to_owned()),
            column: "id".to_owned(),
        },
        Expression::ColumnRef {
            table: Some("users".to_owned()),
            column: "id".to_owned(),
        },
    ]);
    let errors = DialectValidator::validate(&plan, &restricted_profile())
        .expect_err("3 GROUP BY columns should exceed the cap of 2");
    assert_validation_error(&errors, |kind| {
        matches!(kind, ValidationErrorKind::AggregationMismatch { .. })
    });
}

// ---------------------------------------------------------------------
// 6. Combined: a plan that violates several features at once collects
//    every error rather than failing fast on the first one.
// ---------------------------------------------------------------------

#[test]
fn multiple_dialect_violations_are_collected_together() {
    let mut plan = base_plan();
    plan.ctes = Some(vec![vlorql_core::schema::CommonTableExpression {
        name: "staging".to_owned(),
        recursive: false,
        query: Box::new(base_plan()),
    }]);
    plan.joins = Some(vec![
        JoinClause {
            join_type: JoinType::Right,
            right_table: FromClause::table("users".to_owned(), Some("u2".to_owned())),
            on: Predicate::Comparison {
                left: Box::new(Expression::ColumnRef {
                    table: Some("users".to_owned()),
                    column: "id".to_owned(),
                }),
                op: ComparisonOperator::Eq,
                right: Box::new(Expression::ColumnRef {
                    table: Some("u2".to_owned()),
                    column: "id".to_owned(),
                }),
            },
        },
        JoinClause {
            join_type: JoinType::Right,
            right_table: FromClause::table("users".to_owned(), Some("u3".to_owned())),
            on: Predicate::Comparison {
                left: Box::new(Expression::ColumnRef {
                    table: Some("users".to_owned()),
                    column: "id".to_owned(),
                }),
                op: ComparisonOperator::Eq,
                right: Box::new(Expression::ColumnRef {
                    table: Some("u3".to_owned()),
                    column: "id".to_owned(),
                }),
            },
        },
        JoinClause {
            join_type: JoinType::Right,
            right_table: FromClause::table("users".to_owned(), Some("u4".to_owned())),
            on: Predicate::Comparison {
                left: Box::new(Expression::ColumnRef {
                    table: Some("users".to_owned()),
                    column: "id".to_owned(),
                }),
                op: ComparisonOperator::Eq,
                right: Box::new(Expression::ColumnRef {
                    table: Some("u4".to_owned()),
                    column: "id".to_owned(),
                }),
            },
        },
    ]);
    plan.offset = Some(7);
    plan.select = vec![Projection::Expr {
        expression: Expression::FunctionCall {
            name: "load_extension".to_owned(),
            args: Box::new(vec![Expression::Literal {
                value: serde_json::Value::String("/tmp/evil.so".to_owned()),
                data_type: DataType::String,
            }]),
            distinct: true,
        },
        alias: None,
    }];
    let errors = DialectValidator::validate(&plan, &restricted_profile())
        .expect_err("every violation should be reported");
    let codes: std::collections::HashSet<_> = errors.iter().map(VlorQLError::error_code).collect();
    assert!(codes.contains("V005"), "missing V005: {codes:?}");
    assert!(codes.contains("V007"), "missing V007: {codes:?}");
    assert!(codes.contains("V008"), "missing V008: {codes:?}");
}

// ---------------------------------------------------------------------
// 7. Sanity: a fully valid plan passes
// ---------------------------------------------------------------------

#[test]
fn plan_that_respects_every_constraint_passes_validation() {
    let plan = QueryPlan {
        select: vec![Projection::Column {
            table: Some("users".to_owned()),
            column: "id".to_owned(),
            alias: None,
        }],
        from: FromClause::table("users".to_owned(), None),
        r#where: None,
        group_by: None,
        having: None,
        order_by: None,
        limit: None,
        offset: None,
        joins: None,
        ctes: None,
        distinct: false,
        distinct_on: None,
        set_operation: None,
    };
    DialectValidator::validate(&plan, &restricted_profile())
        .expect("a trivial plan should respect the strict profile");
}

// Keep the schema import non-`#[allow(dead_code)]` by referencing it in
// a no-op assertion. (The `TableSchema` helper above is only used in
// `base_plan`; the import is needed for `CommonTableExpression`.)
#[allow(dead_code)]
fn _force_schema_import() {
    let _ = Arc::new(vlorql_core::schema::SchemaSnapshot::new(
        Vec::<TableSchema>::new(),
        SchemaMetadata::default(),
    ));
}