partiql-eval 0.14.0

PartiQL Expression Evaluator
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
use crate::eval::eval_expr_wrapper::UnaryValueExpr;
use crate::eval::expr::{BindError, BindEvalExpr, EvalExpr};
use crate::eval::graph::evaluator::GraphEvaluator;
use crate::eval::graph::simple_graph::engine::SimpleGraphEngine;

use crate::eval::graph::plan::PathPatternMatch;
use crate::eval::graph::string_graph::StringGraphTypes;
use partiql_types::{type_graph, PartiqlNoIdShapeBuilder};
use partiql_value::Value::Missing;
use partiql_value::{Graph, Value};

/// Represents an evaluation `MATCH` operator, e.g. in `graph MATCH () -> ()'`.
#[derive(Debug)]
pub(crate) struct EvalGraphMatch {
    pub(crate) pattern: PathPatternMatch<StringGraphTypes>,
}

impl EvalGraphMatch {
    pub(crate) fn new(pattern: PathPatternMatch<StringGraphTypes>) -> Self {
        EvalGraphMatch { pattern }
    }
}

impl BindEvalExpr for EvalGraphMatch {
    fn bind<const STRICT: bool>(
        self,
        args: Vec<Box<dyn EvalExpr>>,
    ) -> Result<Box<dyn EvalExpr>, BindError> {
        // use DummyShapeBuilder, as we don't care about shape Ids for evaluation dispatch
        let mut bld = PartiqlNoIdShapeBuilder::default();
        UnaryValueExpr::create_typed_with_ctx::<{ STRICT }, _>(
            [type_graph!(bld)],
            args,
            move |value, ctx| match value {
                Value::Graph(graph) => match graph.as_ref() {
                    Graph::Simple(g) => {
                        let engine = SimpleGraphEngine::new(g.clone());
                        let ge = GraphEvaluator::new(engine);
                        ge.eval(&self.pattern, ctx)
                    }
                },
                _ => Missing,
            },
        )
    }
}

#[cfg(test)]
mod tests {
    use crate::eval::expr::{BindEvalExpr, EvalGlobalVarRef, EvalGraphMatch};
    use crate::eval::graph::plan::{
        BindSpec, DirectionFilter, EdgeFilter, LabelFilter, NodeFilter, NodeMatch, PathMode,
        PathPatternMatch, TripleFilter, TripleStepFilter, TripleStepMatch, ValueFilter,
    };
    use crate::eval::graph::string_graph::StringGraphTypes;
    use crate::eval::graph::types::GraphTypes;
    use crate::eval::{BasicContext, MapBindings};
    use crate::test_value::TestValue;
    use partiql_catalog::context::SystemContext;
    use partiql_common::pretty::ToPretty;
    use partiql_logical::graph::bind_name::FreshBinder;
    use partiql_value::datum::DatumTupleRef;
    use partiql_value::{tuple, BindingsName, DateTime, Value};

    impl<GT: GraphTypes> From<TripleStepMatch<GT>> for PathPatternMatch<GT> {
        fn from(value: TripleStepMatch<GT>) -> Self {
            Self::Match(value)
        }
    }

    impl<GT: GraphTypes> From<NodeMatch<GT>> for PathPatternMatch<GT> {
        fn from(value: NodeMatch<GT>) -> Self {
            Self::Node(value)
        }
    }

    pub trait ElementFilterBuilder<GT: GraphTypes> {
        fn any() -> Self;
        fn labeled(label: GT::Label) -> Self;
    }

    impl<GT: GraphTypes> ElementFilterBuilder<GT> for NodeFilter<GT> {
        fn any() -> Self {
            Self {
                label: LabelFilter::Always,
                filter: ValueFilter::Always,
            }
        }

        fn labeled(label: GT::Label) -> Self {
            Self {
                label: LabelFilter::Named(label),
                filter: ValueFilter::Always,
            }
        }
    }

    impl<GT: GraphTypes> ElementFilterBuilder<GT> for EdgeFilter<GT> {
        fn any() -> Self {
            Self {
                label: LabelFilter::Always,
                filter: ValueFilter::Always,
            }
        }
        fn labeled(label: GT::Label) -> Self {
            Self {
                label: LabelFilter::Named(label),
                filter: ValueFilter::Always,
            }
        }
    }

    /*
        A simple 3-node, 3-edge graph which is intended to be able to be exactly matched by:
       ```(graph MATCH
            (n1:a WHERE n1 == 1) -[e12:e WHERE e12 == 1.2]-> (n2),
            (n2:b WHERE n2 == 2) -[e23:d WHERE e23 == 2.3]-> (n3),
            (n3:a WHERE n3 == 3) ~[e_u:self WHERE e_u == <<>>]~ (n3)
        )```
    */
    fn graph() -> Value {
        let graph = r##"
            $graph::{
                nodes: [ {id: n1, labels: ["a"], payload: 1},
                         {id: n2, labels: ["b"], payload: 2},
                         {id: n3, labels: ["a"], payload: 3} ],
                edges: [ {id: e12, labels: ["e"], payload: 1.2, ends: (n1 -> n2) },
                         {id: e23, labels: ["d"], payload: 2.3, ends: (n2 -> n3) },
                         {id: e_u, labels: ["self"], payload: $bag::[] , ends: (n3 -- n3) } ]
            }
            "##;
        TestValue::from(graph).value
    }

    fn bindings() -> MapBindings<Value> {
        let mut bindings: MapBindings<Value> = MapBindings::default();
        bindings.insert("graph", graph());
        bindings
    }

    fn context() -> BasicContext<'static> {
        let sys = SystemContext {
            now: DateTime::from_system_now_utc(),
        };
        let ctx = BasicContext::new(bindings(), sys);
        ctx
    }

    fn graph_reference() -> Box<EvalGlobalVarRef> {
        Box::new(EvalGlobalVarRef {
            name: BindingsName::CaseInsensitive("graph".to_string().into()),
        })
    }

    #[track_caller]
    fn test_graph(matcher: PathPatternMatch<StringGraphTypes>, expected: &'static str) {
        let eval = EvalGraphMatch::new(matcher)
            .bind::<false>(vec![graph_reference()])
            .expect("graph match bind");

        let bindings = tuple![("graph", graph())];
        let bindings = DatumTupleRef::Tuple(&bindings);
        let ctx = context();
        let res = eval.evaluate(&bindings, &ctx);
        let expected = crate::test_value::parse_partiql_value_str(expected);

        let pretty = |v: &Value| v.to_pretty_string(80).unwrap();

        assert_eq!(pretty(&expected), pretty(res.as_ref()));
    }

    #[test]
    fn node() {
        // Query: (graph MATCH (x:a))
        let binder = BindSpec("x".to_string());
        let spec = NodeFilter::labeled("a".to_string());
        let matcher = NodeMatch { binder, spec };

        test_graph(matcher.into(), "<< { 'x': 1 }, { 'x': 3 } >>")
    }

    #[test]
    fn no_edge_matches() {
        let fresh = FreshBinder::default();

        // Query: (graph MATCH () -[e:foo]- ())
        let binders = (
            BindSpec(fresh.node()),
            BindSpec("e".to_string()),
            BindSpec(fresh.node()),
        );
        let spec = TripleStepFilter {
            dir: DirectionFilter::LUR,
            triple: TripleFilter {
                lhs: NodeFilter::any(),
                e: EdgeFilter::labeled("foo".to_string()),
                rhs: NodeFilter::any(),
            },
        };

        let matcher: TripleStepMatch<StringGraphTypes> = TripleStepMatch {
            binders,
            spec,
            filter: ValueFilter::Always,
            path_mode: PathMode::Walk,
        };

        test_graph(matcher.into(), "<<  >>")
    }

    #[test]
    fn no_node_matches() {
        let fresh = FreshBinder::default();

        // Query: (graph MATCH (:foo) -[]- ())
        let binders = (
            BindSpec(fresh.node()),
            BindSpec(fresh.edge()),
            BindSpec(fresh.node()),
        );
        let spec = TripleStepFilter {
            dir: DirectionFilter::LUR,
            triple: TripleFilter {
                lhs: NodeFilter::labeled("foo".to_string()),
                e: EdgeFilter::any(),
                rhs: NodeFilter::any(),
            },
        };

        let matcher: TripleStepMatch<StringGraphTypes> = TripleStepMatch {
            binders,
            spec,
            filter: ValueFilter::Always,
            path_mode: PathMode::Walk,
        };

        test_graph(matcher.into(), "<<  >>")
    }

    #[test]
    fn node_edge_node() {
        // Query: (graph MATCH (x)<-[z:e]-(y))
        let binders = (
            BindSpec("x".to_string()),
            BindSpec("z".to_string()),
            BindSpec("y".to_string()),
        );
        let spec = TripleStepFilter {
            dir: DirectionFilter::L,
            triple: TripleFilter {
                lhs: NodeFilter::any(),
                e: EdgeFilter::labeled("e".to_string()),
                rhs: NodeFilter::any(),
            },
        };

        let matcher: TripleStepMatch<StringGraphTypes> = TripleStepMatch {
            binders,
            spec,
            filter: ValueFilter::Always,
            path_mode: PathMode::Walk,
        };

        test_graph(matcher.into(), "<< {'x': 2, 'z': 1.2, 'y': 1} >>")
    }

    #[test]
    fn edge() {
        let fresh = FreshBinder::default();

        // Query: (graph MATCH -> )
        let binders = (
            BindSpec(fresh.node()),
            BindSpec(fresh.edge()),
            BindSpec(fresh.node()),
        );
        let spec = TripleStepFilter {
            dir: DirectionFilter::R,
            triple: TripleFilter {
                lhs: NodeFilter::any(),
                e: EdgeFilter::any(),
                rhs: NodeFilter::any(),
            },
        };

        let matcher: TripleStepMatch<StringGraphTypes> = TripleStepMatch {
            binders,
            spec,
            filter: ValueFilter::Always,
            path_mode: PathMode::Walk,
        };

        test_graph(matcher.into(), "<< {  }, {  } >>")
    }

    #[test]
    fn edge_outgoing() {
        let fresh = FreshBinder::default();

        // Query: (graph MATCH <-[z]-> )
        let binders = (
            BindSpec(fresh.node()),
            BindSpec("z".to_string()),
            BindSpec(fresh.node()),
        );
        let spec = TripleStepFilter {
            dir: DirectionFilter::LR,
            triple: TripleFilter {
                lhs: NodeFilter::any(),
                e: EdgeFilter::any(),
                rhs: NodeFilter::any(),
            },
        };

        let matcher: TripleStepMatch<StringGraphTypes> = TripleStepMatch {
            binders,
            spec,
            filter: ValueFilter::Always,
            path_mode: PathMode::Walk,
        };

        test_graph(
            matcher.into(),
            "<< { 'z': 1.2 }, { 'z': 1.2 }, { 'z': 2.3 }, { 'z': 2.3 } >>",
        )
    }

    #[test]
    fn n_e_n_e_n() {
        // Query: (graph MATCH (x:b)-[z1]-(y1:a)-[z2]-(y2:b) )
        let binders = (
            BindSpec("x".to_string()),
            BindSpec("z1".to_string()),
            BindSpec("y1".to_string()),
        );
        let spec = TripleStepFilter {
            dir: DirectionFilter::LUR,
            triple: TripleFilter {
                lhs: NodeFilter::labeled("b".to_string()),
                e: EdgeFilter::any(),
                rhs: NodeFilter::labeled("a".to_string()),
            },
        };
        let matcher1: TripleStepMatch<StringGraphTypes> = TripleStepMatch {
            binders,
            spec,
            filter: Default::default(),
            path_mode: PathMode::Walk,
        };

        let binders = (
            BindSpec("y1".to_string()),
            BindSpec("z2".to_string()),
            BindSpec("y2".to_string()),
        );
        let spec = TripleStepFilter {
            dir: DirectionFilter::LUR,
            triple: TripleFilter {
                lhs: NodeFilter::labeled("a".to_string()),
                e: EdgeFilter::any(),
                rhs: NodeFilter::labeled("b".to_string()),
            },
        };
        let matcher2: TripleStepMatch<StringGraphTypes> = TripleStepMatch {
            binders,
            spec,
            filter: Default::default(),
            path_mode: PathMode::Walk,
        };

        let pattern_match = PathPatternMatch::Concat(
            vec![
                PathPatternMatch::Match(matcher1),
                PathPatternMatch::Match(matcher2),
            ],
            Default::default(),
            PathMode::Walk,
        );

        test_graph(
            pattern_match,
            "<< { 'x': 2, 'z1': 1.2, 'y1': 1, 'z2': 1.2, 'y2': 2 }, \
                             { 'x': 2, 'z1': 2.3, 'y1': 3, 'z2': 2.3, 'y2': 2 } >>",
        )
    }
    #[test]
    fn cycle() {
        let fresh = FreshBinder::default();

        // Query: (graph MATCH (x1) - (x2) - (x1))
        let binders = (
            BindSpec("x1".to_string()),
            BindSpec(fresh.edge()),
            BindSpec("x2".to_string()),
        );
        let spec = TripleStepFilter {
            dir: DirectionFilter::LUR,
            triple: TripleFilter {
                lhs: NodeFilter::any(),
                e: EdgeFilter::any(),
                rhs: NodeFilter::any(),
            },
        };
        let matcher1: TripleStepMatch<StringGraphTypes> = TripleStepMatch {
            binders,
            spec,
            filter: Default::default(),
            path_mode: PathMode::Walk,
        };

        let binders = (
            BindSpec("x2".to_string()),
            BindSpec(fresh.edge()),
            BindSpec("x1".to_string()),
        );
        let spec = TripleStepFilter {
            dir: DirectionFilter::LUR,
            triple: TripleFilter {
                lhs: NodeFilter::any(),
                e: EdgeFilter::any(),
                rhs: NodeFilter::any(),
            },
        };
        let matcher2: TripleStepMatch<StringGraphTypes> = TripleStepMatch {
            binders,
            spec,
            filter: Default::default(),
            path_mode: PathMode::Walk,
        };

        let pattern_match = PathPatternMatch::Concat(
            vec![
                PathPatternMatch::Match(matcher1),
                PathPatternMatch::Match(matcher2),
            ],
            Default::default(),
            PathMode::Walk,
        );
        test_graph(
            pattern_match,
            "<< { 'x1': 3, 'x2': 3 }, \
                             { 'x1': 1, 'x2': 2 }, \
                             { 'x1': 2, 'x2': 1 }, \
                             { 'x1': 2, 'x2': 3 }, \
                             { 'x1': 3, 'x2': 2 } >>",
        )
    }
}