linkrs-query 0.1.0

Query engine, parser, and executor for Linkrs
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
use super::*;

use crate::planning::plan::core::nodes::base::plan_node_enum::PlanNodeEnum;
use crate::planning::plan::core::nodes::control_flow::start_node::StartNode;
use crate::planning::plan::core::nodes::operation::FilterNode;
use crate::planning::plan::core::nodes::operation::ProjectNode;
use linkrs_core::types::expr::analysis_utils::is_evaluable;
use linkrs_core::types::expr::ExpressionAnalysisContext;
use linkrs_core::types::expr::ExpressionMeta;
use linkrs_core::types::operators::BinaryOperator;
use linkrs_core::types::ContextualExpression;
use linkrs_core::Value;
use linkrs_core::YieldColumn;
use std::sync::Arc;

fn contextual(expr_ctx: &Arc<ExpressionAnalysisContext>, expr: Expression) -> ContextualExpression {
    let meta = ExpressionMeta::new(expr);
    let id = expr_ctx.register_expression(meta);
    ContextualExpression::new(id, expr_ctx.clone())
}

#[test]
fn test_fold_rule_name() {
    let rule = FoldConstantsRule::new();
    assert_eq!(rule.name(), "FoldConstantsRule");
}

#[test]
fn test_fold_binary_constant() {
    let expr = Expression::Binary {
        left: Box::new(Expression::Literal(Value::Int(1))),
        op: BinaryOperator::Add,
        right: Box::new(Expression::Literal(Value::Int(2))),
    };
    assert!(is_evaluable(&expr));
    let folded = FoldConstantsRule::fold_expression(&expr);
    assert_eq!(folded, Expression::Literal(Value::Int(3)));
}

#[test]
fn test_fold_with_variable_is_not_folded() {
    let expr = Expression::Binary {
        left: Box::new(Expression::Variable("x".to_string())),
        op: BinaryOperator::Add,
        right: Box::new(Expression::Literal(Value::Int(2))),
    };
    let folded = FoldConstantsRule::fold_expression(&expr);
    assert_eq!(folded, expr, "expressions with variables must not fold");
}

#[test]
fn test_fold_partial_constant_subexpression() {
    let expr = Expression::Binary {
        left: Box::new(Expression::Binary {
            left: Box::new(Expression::Literal(Value::Int(1))),
            op: BinaryOperator::Add,
            right: Box::new(Expression::Literal(Value::Int(2))),
        }),
        op: BinaryOperator::Add,
        right: Box::new(Expression::Variable("x".to_string())),
    };
    let folded = FoldConstantsRule::fold_expression(&expr);
    assert_eq!(
        folded,
        Expression::Binary {
            left: Box::new(Expression::Literal(Value::Int(3))),
            op: BinaryOperator::Add,
            right: Box::new(Expression::Variable("x".to_string())),
        },
        "constant sub-expressions fold, the variable part stays"
    );
}

#[test]
fn test_fold_impure_function_is_not_folded() {
    let expr = Expression::Function {
        name: "rand".to_string(),
        args: vec![],
    };
    assert!(is_evaluable(&expr), "rand has no context dependency");
    let folded = FoldConstantsRule::fold_expression(&expr);
    assert_eq!(folded, expr, "impure functions must never fold");
}

#[test]
fn test_fold_unregistered_function_is_not_folded() {
    // A function name that is not in the registry must conservatively
    // stay unfolded even though it carries no context dependency.
    let expr = Expression::Function {
        name: "future_nondeterministic_fn".to_string(),
        args: vec![FunctionArg::Positional(Expression::Literal(Value::Int(1)))],
    };
    assert!(is_evaluable(&expr), "no context dependency");
    let folded = FoldConstantsRule::fold_expression(&expr);
    assert_eq!(folded, expr, "unregistered functions must never fold");
}

#[test]
fn test_fold_pure_builtin_function() {
    let expr = Expression::Function {
        name: "abs".to_string(),
        args: vec![FunctionArg::Positional(Expression::Literal(Value::Int(-5)))],
    };
    let folded = FoldConstantsRule::fold_expression(&expr);
    assert_eq!(
        folded,
        Expression::Literal(Value::Int(5)),
        "pure builtin functions fold"
    );
}

#[test]
fn test_fold_aggregate_is_not_folded() {
    let expr = Expression::Aggregate {
        func: linkrs_core::AggregateFunction::Count,
        args: vec![Expression::Literal(Value::Int(1))],
        distinct: false,
        filter: None,
    };
    let folded = FoldConstantsRule::fold_expression(&expr);
    assert_eq!(folded, expr, "aggregates need a row-group context");
}

#[test]
fn test_fold_filter_node_condition() {
    let expr_ctx = Arc::new(ExpressionAnalysisContext::new());
    let start = PlanNodeEnum::Start(StartNode::new());
    let condition = contextual(
        &expr_ctx,
        Expression::Binary {
            left: Box::new(Expression::Literal(Value::Int(1))),
            op: BinaryOperator::Equal,
            right: Box::new(Expression::Literal(Value::Int(1))),
        },
    );
    let filter = FilterNode::new(start, condition).expect("filter node");
    let node = PlanNodeEnum::Filter(filter);

    let rule = FoldConstantsRule::new();
    let mut ctx = RewriteContext::new();
    let result = rule.apply(&mut ctx, &node).expect("apply should succeed");
    let result = result.expect("filter with constant condition must fold");
    let new_node = result.new_nodes.first().cloned().expect("replacement node");
    match new_node {
        PlanNodeEnum::Filter(f) => {
            let folded = f
                .condition()
                .expression()
                .expect("expression")
                .inner()
                .clone();
            assert_eq!(
                folded,
                Expression::Literal(Value::Bool(true)),
                "1 = 1 folds to TRUE"
            );
        }
        other => panic!("expected Filter node, got {:?}", other),
    }
}

#[test]
fn test_fold_project_node_columns() {
    let expr_ctx = Arc::new(ExpressionAnalysisContext::new());
    let start = PlanNodeEnum::Start(StartNode::new());
    let column = YieldColumn {
        expression: contextual(
            &expr_ctx,
            Expression::Binary {
                left: Box::new(Expression::Literal(Value::Int(10))),
                op: BinaryOperator::Divide,
                right: Box::new(Expression::Literal(Value::Int(2))),
            },
        ),
        alias: "half".to_string(),
    };
    let project = ProjectNode::new(start, vec![column]).expect("project node");
    let node = PlanNodeEnum::Project(project);

    let rule = FoldConstantsRule::new();
    let mut ctx = RewriteContext::new();
    let result = rule.apply(&mut ctx, &node).expect("apply should succeed");
    let result = result.expect("project with constant column must fold");
    let new_node = result.new_nodes.first().cloned().expect("replacement node");
    match new_node {
        PlanNodeEnum::Project(p) => {
            let folded = p.columns()[0]
                .expression
                .expression()
                .expect("expression")
                .inner()
                .clone();
            assert_eq!(folded, Expression::Literal(Value::Int(5)));
            assert_eq!(p.columns()[0].alias, "half", "alias is preserved");
        }
        other => panic!("expected Project node, got {:?}", other),
    }
}

#[test]
fn test_fold_project_partial_subexpression() {
    // Partial folding: `p.age + (1 + 2)` keeps the variable part but
    // folds the constant sub-expression to `p.age + 3`.
    let expr_ctx = Arc::new(ExpressionAnalysisContext::new());
    let start = PlanNodeEnum::Start(StartNode::new());
    let column = YieldColumn {
        expression: contextual(
            &expr_ctx,
            Expression::Binary {
                left: Box::new(Expression::Variable("p.age".to_string())),
                op: BinaryOperator::Add,
                right: Box::new(Expression::Binary {
                    left: Box::new(Expression::Literal(Value::Int(1))),
                    op: BinaryOperator::Add,
                    right: Box::new(Expression::Literal(Value::Int(2))),
                }),
            },
        ),
        alias: "age_plus".to_string(),
    };
    let project = ProjectNode::new(start, vec![column]).expect("project node");
    let node = PlanNodeEnum::Project(project);

    let rule = FoldConstantsRule::new();
    let mut ctx = RewriteContext::new();
    let result = rule.apply(&mut ctx, &node).expect("apply should succeed");
    let result = result.expect("project with foldable sub-expression must change");
    let new_node = result.new_nodes.first().cloned().expect("replacement node");
    match new_node {
        PlanNodeEnum::Project(p) => {
            let folded = p.columns()[0]
                .expression
                .expression()
                .expect("expression")
                .inner()
                .clone();
            assert_eq!(
                folded,
                Expression::Binary {
                    left: Box::new(Expression::Variable("p.age".to_string())),
                    op: BinaryOperator::Add,
                    right: Box::new(Expression::Literal(Value::Int(3))),
                },
                "constant sub-expression folds, the variable part stays"
            );
        }
        other => panic!("expected Project node, got {:?}", other),
    }
}

#[test]
fn test_fold_assign_node_assignments() {
    use crate::planning::plan::core::nodes::graph_operations::graph_operations_node::AssignNode;

    let expr_ctx = Arc::new(ExpressionAnalysisContext::new());
    let start = PlanNodeEnum::Start(StartNode::new());
    let assignments = vec![
        (
            "c".to_string(),
            contextual(
                &expr_ctx,
                Expression::Binary {
                    left: Box::new(Expression::Literal(Value::Int(1))),
                    op: BinaryOperator::Add,
                    right: Box::new(Expression::Literal(Value::Int(2))),
                },
            ),
        ),
        (
            "partial".to_string(),
            contextual(
                &expr_ctx,
                Expression::Binary {
                    left: Box::new(Expression::Variable("p.age".to_string())),
                    op: BinaryOperator::Subtract,
                    right: Box::new(Expression::Literal(Value::Int(4))),
                },
            ),
        ),
    ];
    let assign = AssignNode::new(start, assignments).expect("assign node");
    let node = PlanNodeEnum::Assign(assign);

    let rule = FoldConstantsRule::new();
    let mut ctx = RewriteContext::new();
    let result = rule.apply(&mut ctx, &node).expect("apply should succeed");
    let result = result.expect("assign with constant assignment must fold");
    let new_node = result.new_nodes.first().cloned().expect("replacement node");
    match new_node {
        PlanNodeEnum::Assign(a) => {
            let (_, folded) = &a.assignments()[0];
            assert_eq!(
                folded.expression().expect("expression").inner().clone(),
                Expression::Literal(Value::Int(3)),
                "constant assignment folds"
            );
            let (_, kept) = &a.assignments()[1];
            assert_eq!(
                kept.expression().expect("expression").inner().clone(),
                Expression::Binary {
                    left: Box::new(Expression::Variable("p.age".to_string())),
                    op: BinaryOperator::Subtract,
                    right: Box::new(Expression::Literal(Value::Int(4))),
                },
                "assignments with variables stay"
            );
        }
        other => panic!("expected Assign node, got {:?}", other),
    }
}

#[test]
fn test_fold_sort_node_items() {
    use crate::planning::plan::core::nodes::operation::sort_node::SortNode;

    let start = PlanNodeEnum::Start(StartNode::new());
    let items = vec![
        crate::planning::plan::core::nodes::operation::sort_node::SortItem::asc(
            Expression::Binary {
                left: Box::new(Expression::Literal(Value::Int(1))),
                op: BinaryOperator::Add,
                right: Box::new(Expression::Literal(Value::Int(2))),
            },
        ),
        crate::planning::plan::core::nodes::operation::sort_node::SortItem::desc(
            Expression::Variable("x".to_string()),
        ),
    ];
    let sort = SortNode::new(start, items).expect("sort node");
    let node = PlanNodeEnum::Sort(sort);

    let rule = FoldConstantsRule::new();
    let mut ctx = RewriteContext::new();
    let result = rule.apply(&mut ctx, &node).expect("apply should succeed");
    let result = result.expect("sort with constant item must fold");
    let new_node = result.new_nodes.first().cloned().expect("replacement node");
    match new_node {
        PlanNodeEnum::Sort(s) => {
            assert_eq!(
                s.sort_items()[0].expression,
                Expression::Literal(Value::Int(3)),
                "constant sort expression folds"
            );
            assert_eq!(
                s.sort_items()[1].expression,
                Expression::Variable("x".to_string()),
                "variable sort expression stays"
            );
        }
        other => panic!("expected Sort node, got {:?}", other),
    }
}

#[test]
fn test_fold_window_node_specs() {
    use crate::planning::plan::core::nodes::graph_operations::window_node::{
        WindowFunctionSpec, WindowNode,
    };

    let start = PlanNodeEnum::Start(StartNode::new());
    let spec = WindowFunctionSpec {
        name: "rank".to_string(),
        args: vec![Expression::Literal(Value::Int(1))],
        partition_by: vec![Expression::Binary {
            left: Box::new(Expression::Literal(Value::Int(10))),
            op: BinaryOperator::Subtract,
            right: Box::new(Expression::Literal(Value::Int(2))),
        }],
        order_by: vec![Expression::Variable("x".to_string())],
        order_desc: vec![false],
    };
    let window = WindowNode::new(start, vec![spec]).expect("window node");
    let node = PlanNodeEnum::Window(window);

    let rule = FoldConstantsRule::new();
    let mut ctx = RewriteContext::new();
    let result = rule.apply(&mut ctx, &node).expect("apply should succeed");
    let result = result.expect("window with constant spec must fold");
    let new_node = result.new_nodes.first().cloned().expect("replacement node");
    match new_node {
        PlanNodeEnum::Window(w) => {
            assert_eq!(
                w.window_functions()[0].args,
                vec![Expression::Literal(Value::Int(1))],
                "already-literal args stay"
            );
            assert_eq!(
                w.window_functions()[0].partition_by,
                vec![Expression::Literal(Value::Int(8))],
                "constant partition expression folds"
            );
            assert_eq!(
                w.window_functions()[0].order_by,
                vec![Expression::Variable("x".to_string())],
                "variable order expression stays"
            );
        }
        other => panic!("expected Window node, got {:?}", other),
    }
}

#[test]
fn test_fold_aggregate_node_filters() {
    use crate::planning::plan::core::nodes::graph_operations::aggregate_node::AggregateNode;
    use linkrs_core::AggregateFunction;

    let start = PlanNodeEnum::Start(StartNode::new());
    let aggregate =
        AggregateNode::new(start, vec!["g".to_string()], vec![AggregateFunction::Count])
            .expect("aggregate node");
    let mut aggregate = aggregate.clone();
    aggregate.set_aggregation_filters(vec![Some(Expression::Binary {
        left: Box::new(Expression::Literal(Value::Int(1))),
        op: BinaryOperator::Equal,
        right: Box::new(Expression::Literal(Value::Int(1))),
    })]);
    let node = PlanNodeEnum::Aggregate(aggregate);

    let rule = FoldConstantsRule::new();
    let mut ctx = RewriteContext::new();
    let result = rule.apply(&mut ctx, &node).expect("apply should succeed");
    let result = result.expect("aggregate with constant filter must fold");
    let new_node = result.new_nodes.first().cloned().expect("replacement node");
    match new_node {
        PlanNodeEnum::Aggregate(a) => {
            assert_eq!(
                a.aggregation_filters()[0],
                Some(Expression::Literal(Value::Bool(true))),
                "constant aggregate filter folds"
            );
        }
        other => panic!("expected Aggregate node, got {:?}", other),
    }
}

#[test]
fn test_fold_inner_join_keys() {
    use crate::planning::plan::core::nodes::join::join_node::InnerJoinNode;

    let expr_ctx = Arc::new(ExpressionAnalysisContext::new());
    let left = PlanNodeEnum::Start(StartNode::new());
    let right = PlanNodeEnum::Start(StartNode::new());
    let hash_keys = vec![contextual(
        &expr_ctx,
        Expression::Binary {
            left: Box::new(Expression::Literal(Value::Int(1))),
            op: BinaryOperator::Add,
            right: Box::new(Expression::Literal(Value::Int(2))),
        },
    )];
    let probe_keys = vec![contextual(
        &expr_ctx,
        Expression::Variable("r.id".to_string()),
    )];
    let join = InnerJoinNode::new(left, right, hash_keys, probe_keys).expect("join node");
    let node = PlanNodeEnum::InnerJoin(join);

    let rule = FoldConstantsRule::new();
    let mut ctx = RewriteContext::new();
    let result = rule.apply(&mut ctx, &node).expect("apply should succeed");
    let result = result.expect("join with constant key must fold");
    let new_node = result.new_nodes.first().cloned().expect("replacement node");
    match new_node {
        PlanNodeEnum::InnerJoin(j) => {
            assert_eq!(
                j.hash_keys()[0]
                    .expression()
                    .expect("expression")
                    .inner()
                    .clone(),
                Expression::Literal(Value::Int(3)),
                "constant join key folds"
            );
            assert_eq!(
                j.probe_keys()[0]
                    .expression()
                    .expect("expression")
                    .inner()
                    .clone(),
                Expression::Variable("r.id".to_string()),
                "variable join key stays"
            );
        }
        other => panic!("expected InnerJoin node, got {:?}", other),
    }
}

#[test]
fn test_fold_does_not_touch_unchanged_nodes() {
    let start = PlanNodeEnum::Start(StartNode::new());
    let items = vec![
        crate::planning::plan::core::nodes::operation::sort_node::SortItem::asc(
            Expression::Variable("x".to_string()),
        ),
    ];
    let sort = SortNode::new(start, items).expect("sort node");
    let node = PlanNodeEnum::Sort(sort);

    let rule = FoldConstantsRule::new();
    let mut ctx = RewriteContext::new();
    let result = rule.apply(&mut ctx, &node).expect("apply should succeed");
    assert!(
        result.is_none(),
        "sort with only variable expressions must not change"
    );
}