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
//! Typed schema and query-plan models.

pub mod dialect;
pub mod expressions;
pub mod query_plan;
pub mod snapshot;
pub mod types;

pub use dialect::{DialectProfile, DialectProfileBuilder};
pub use expressions::{
    Expression, InTarget, Predicate, WhenThen, WindowFrame, WindowFrameBound, WindowFrameKind,
    WindowSpec,
};
pub use query_plan::{
    CommonTableExpression, FromClause, JoinClause, OrderByTerm, Projection, QueryPlan,
    SetOperation, SetOperationClause,
};
pub use snapshot::{
    ArcSchemaSnapshot, ColumnSchema, ForeignKey, SchemaMetadata, SchemaSnapshot, TableSchema,
};
pub use types::{
    BinaryOperator, ComparisonOperator, DataType, IdentifierQuoting, JoinType, SqlDialect,
};

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{from_value, json, to_value};
    use std::sync::Arc;

    fn simple_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: Some(Predicate::Comparison {
                left: Box::new(Expression::ColumnRef {
                    table: Some("users".to_owned()),
                    column: "active".to_owned(),
                }),
                op: ComparisonOperator::Eq,
                right: Box::new(Expression::Literal {
                    value: json!(true),
                    data_type: DataType::Boolean,
                }),
            }),
            group_by: None,
            having: None,
            order_by: None,
            limit: Some(25),
            offset: None,
            joins: None,
            ctes: None,
            distinct: false,
            distinct_on: None,
            set_operation: None,
        }
    }

    #[test]
    fn query_plan_round_trips_and_omits_missing_pagination_fields() {
        let plan = simple_plan();
        let value = to_value(&plan).expect("query plan should serialize");
        assert_eq!(value["limit"], 25);
        assert!(value.get("offset").is_none());

        let decoded: QueryPlan = from_value(value).expect("query plan should deserialize");
        assert_eq!(decoded, plan);
    }

    #[test]
    fn query_plan_rejects_unknown_fields() {
        let mut value = to_value(simple_plan()).expect("query plan should serialize");
        value
            .as_object_mut()
            .expect("plan should be an object")
            .insert("unexpected".to_owned(), json!(true));

        let error = from_value::<QueryPlan>(value).expect_err("unknown fields must be rejected");
        assert!(error.to_string().contains("unknown field"));
    }

    #[test]
    fn tagged_expression_and_predicate_reject_unknown_fields() {
        let expression = json!({
            "type": "column_ref",
            "table": "users",
            "column": "id",
            "unexpected": true
        });
        let predicate = json!({
            "type": "is_null",
            "expr": {
                "type": "column_ref",
                "table": "users",
                "column": "deleted_at"
            },
            "unexpected": true
        });

        assert!(from_value::<Expression>(expression).is_err());
        assert!(from_value::<Predicate>(predicate).is_err());
    }

    #[test]
    fn schema_snapshot_uses_indexed_table_and_column_lookup() {
        let snapshot = SchemaSnapshot::new(
            vec![TableSchema {
                name: "users".to_owned(),
                columns: vec![ColumnSchema {
                    name: "id".to_owned(),
                    data_type: DataType::Uuid,
                    nullable: false,
                    description: None,
                    is_primary_key: true,
                    foreign_key: None,
                }],
                description: None,
                primary_key: Some(vec!["id".to_owned()]),
            }],
            SchemaMetadata::default(),
        );

        assert_eq!(
            snapshot.get_table("users").map(|table| table.name.as_str()),
            Some("users")
        );
        assert_eq!(
            snapshot
                .get_column("users", "id")
                .map(|column| column.data_type),
            Some(DataType::Uuid)
        );
        assert!(snapshot.get_table("missing").is_none());
        assert!(snapshot.get_column("users", "missing").is_none());

        let serialized = to_value(&snapshot).expect("schema snapshot should serialize");
        assert!(serialized.get("table_index").is_none());
        assert!(serialized["tables"].is_array());

        let restored: SchemaSnapshot = from_value(serialized).expect("snapshot should deserialize");
        assert!(restored.get_table("users").is_some());
    }

    #[test]
    fn arc_schema_snapshot_shares_ownership() {
        let snapshot = Arc::new(SchemaSnapshot::default());
        let shared: ArcSchemaSnapshot = Arc::clone(&snapshot);
        assert_eq!(Arc::strong_count(&snapshot), 2);
        assert_eq!(shared.table_count(), 0);
    }

    #[test]
    fn dialect_profile_defaults_match_expected_values() {
        let profile = DialectProfile::default();
        assert_eq!(profile.dialect, SqlDialect::Postgres);
        assert_eq!(profile.quote_style, IdentifierQuoting::DoubleQuote);
        assert!(profile.supports_cte);
        assert!(profile.supports_offset);
    }

    #[test]
    fn query_plan_optional_fields_default_to_none_when_omitted() {
        // `where`, `group_by`, `having`, `order_by`, `limit`, `offset`,
        // `joins`, and `ctes` are all `#[serde(default)]`. A JSON body
        // that omits them must deserialize successfully and round-trip
        // to the same plan.
        let body = json!({
            "select": [{
                "type": "column_ref",
                "table": "users",
                "column": "id",
                "alias": null
            }],
            "from": {"type": "table", "table": "users", "alias": null}
        });
        let plan: QueryPlan = from_value(body).expect("optional fields may be omitted");
        assert!(plan.r#where.is_none());
        assert!(plan.group_by.is_none());
        assert!(plan.having.is_none());
        assert!(plan.order_by.is_none());
        assert!(plan.limit.is_none());
        assert!(plan.offset.is_none());
        assert!(plan.joins.is_none());
        assert!(plan.ctes.is_none());

        let restored_value = to_value(&plan).expect("plan should serialize");
        // `limit` and `offset` use `skip_serializing_if = "Option::is_none"`.
        assert!(restored_value.get("limit").is_none());
        assert!(restored_value.get("offset").is_none());
    }

    #[test]
    fn query_plan_round_trip_preserves_limit_and_offset_when_set() {
        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: Some(50),
            offset: Some(100),
            joins: None,
            ctes: None,
            distinct: false,
            distinct_on: None,
            set_operation: None,
        };
        let value = to_value(&plan).expect("plan should serialize");
        assert_eq!(value["limit"], 50);
        assert_eq!(value["offset"], 100);
        let restored: QueryPlan = from_value(value).expect("plan should round-trip");
        assert_eq!(restored, plan);
    }

    #[test]
    fn from_clause_rejects_unknown_fields() {
        let body = json!({"type": "table", "table": "users", "alias": null, "sneaky": 1});
        let error = from_value::<FromClause>(body).expect_err("unknown FromClause field");
        assert!(error.to_string().contains("sneaky") || error.to_string().contains("unknown"));
    }

    #[test]
    fn schema_snapshot_lookup_helpers_distinguish_table_and_column() {
        let snapshot = SchemaSnapshot::new(
            vec![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: "email".to_owned(),
                        data_type: DataType::String,
                        nullable: true,
                        description: None,
                        is_primary_key: false,
                        foreign_key: None,
                    },
                ],
                description: None,
                primary_key: Some(vec!["id".to_owned()]),
            }],
            SchemaMetadata::default(),
        );

        // Direct table lookup.
        assert_eq!(snapshot.table_count(), 1);
        assert_eq!(snapshot.get_table("users").unwrap().name, "users");
        assert!(snapshot.get_table("missing").is_none());

        // Column lookup.
        assert_eq!(
            snapshot.get_column("users", "id").map(|c| c.data_type),
            Some(DataType::Int)
        );
        assert_eq!(
            snapshot.get_column("users", "email").map(|c| c.nullable),
            Some(true)
        );
        // Unknown column on a known table.
        assert!(snapshot.get_column("users", "missing").is_none());
        // Unknown table always wins over column name.
        assert!(snapshot.get_column("missing", "id").is_none());
    }

    #[test]
    fn schema_snapshot_set_tables_replaces_index() {
        let mut snapshot = SchemaSnapshot::new(
            vec![TableSchema {
                name: "old".to_owned(),
                columns: vec![ColumnSchema {
                    name: "id".to_owned(),
                    data_type: DataType::Int,
                    nullable: false,
                    description: None,
                    is_primary_key: true,
                    foreign_key: None,
                }],
                description: None,
                primary_key: Some(vec!["id".to_owned()]),
            }],
            SchemaMetadata::default(),
        );
        assert!(snapshot.get_table("old").is_some());

        snapshot.set_tables(vec![TableSchema {
            name: "new".to_owned(),
            columns: vec![ColumnSchema {
                name: "id".to_owned(),
                data_type: DataType::Int,
                nullable: false,
                description: None,
                is_primary_key: true,
                foreign_key: None,
            }],
            description: None,
            primary_key: Some(vec!["id".to_owned()]),
        }]);
        assert!(snapshot.get_table("new").is_some());
        assert!(snapshot.get_table("old").is_none());
    }

    #[test]
    fn schema_snapshot_serializes_without_table_index() {
        let snapshot = SchemaSnapshot::default();
        let value = to_value(&snapshot).expect("snapshot should serialize");
        // The internal `table_index` is marked `#[serde(skip)]`.
        assert!(value.get("table_index").is_none());
        assert_eq!(value["tables"], json!([]));
    }

    #[test]
    fn dialect_profile_builder_accepts_all_fields() {
        let profile = DialectProfile::builder()
            .dialect(SqlDialect::Sqlite)
            .quote_style(IdentifierQuoting::Backtick)
            .supports_cte(false)
            .supports_window_functions(true)
            .supports_json_operations(false)
            .max_joins(3usize)
            .allowed_join_types(vec![JoinType::Inner, JoinType::Left])
            .allowed_functions(vec!["count".to_owned()])
            .denied_functions(vec!["load_extension".to_owned()])
            .max_group_by_columns(4usize)
            .allow_distinct(false)
            .supports_offset(false)
            .supports_fetch(false)
            .build()
            .expect("fully configured profile should build");
        assert_eq!(profile.dialect, SqlDialect::Sqlite);
        assert_eq!(profile.quote_style, IdentifierQuoting::Backtick);
        assert!(!profile.supports_cte);
        assert!(profile.supports_window_functions);
        assert!(!profile.supports_json_operations);
        assert_eq!(profile.max_joins, Some(3));
        assert_eq!(
            profile.allowed_join_types,
            vec![JoinType::Inner, JoinType::Left]
        );
        assert_eq!(profile.allowed_functions, vec!["count".to_owned()]);
        assert_eq!(profile.denied_functions, vec!["load_extension".to_owned()]);
        assert_eq!(profile.max_group_by_columns, Some(4));
        assert!(!profile.allow_distinct);
        assert!(!profile.supports_offset);
        assert!(!profile.supports_fetch);
    }

    #[test]
    fn dialect_profile_builder_fills_unspecified_fields_with_defaults() {
        let profile = DialectProfile::builder()
            .dialect(SqlDialect::Sqlite)
            .build()
            .expect("partial profile should build");
        // Every unspecified field must come from `DialectProfile::default()`.
        assert_eq!(profile.quote_style, IdentifierQuoting::DoubleQuote);
        assert!(profile.supports_cte);
        assert!(profile.supports_window_functions);
        assert!(profile.supports_json_operations);
        assert!(profile.max_joins.is_none());
        assert!(profile.max_group_by_columns.is_none());
        assert!(profile.allow_distinct);
        assert!(profile.supports_offset);
        assert!(profile.supports_fetch);
        assert_eq!(
            profile.allowed_join_types,
            DialectProfile::default().allowed_join_types
        );
        assert!(profile.allowed_functions.is_empty());
        assert!(profile.denied_functions.is_empty());
    }

    #[test]
    fn dialect_profile_default_has_postgres_shape() {
        let profile = DialectProfile::default();
        assert_eq!(profile.dialect, SqlDialect::Postgres);
        assert_eq!(profile.quote_style, IdentifierQuoting::DoubleQuote);
        assert!(profile.supports_cte);
        assert!(profile.supports_offset);
        assert!(profile.allow_distinct);
        assert_eq!(
            profile.allowed_join_types,
            vec![
                JoinType::Inner,
                JoinType::Left,
                JoinType::Right,
                JoinType::Full,
                JoinType::Cross,
            ]
        );
    }
}