graphersal 0.1.1

In-memory graph traversal engine modelled on Apache TinkerPop Gremlin, with a Rhai DSL, optimizer and GraphSON/GraphML I/O
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
use crate::graph::GraphStorage;
use crate::*;

#[derive(Default, Clone)]
struct StepAddV {
    /// The vertex's initial label set, in the order given. `None` means no labels (was
    /// `add_v()`/`add_v(None)`); `Some(vec![])` never occurs — an empty list argument still yields
    /// `None` here, matching `add_v()`'s no-label call.
    args: Option<Vec<String>>,
    /// The user-supplied id from a folded `property(T.id, v)`; `None` lets storage assign one.
    id: Option<CompactString>,
    /// The properties the vertex is created with, folded in by the `add_property_fold` rule;
    /// empty when the rule did not fire. Built once per step, cloned per created vertex.
    properties: PropertyMap,
}

impl fmt::Display for StepAddV {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "add_v({}", display_option_vec_string(&self.args))?;
        if !self.properties.is_empty() {
            let sep = if self.args.is_some() { ", " } else { "" };
            let keys: Vec<&str> = self.properties.keys().map(|k| k.as_str()).collect();
            write!(
                f,
                "{sep}properties: {}",
                crate::value::literal::rhai_string_array(&keys)
            )?;
        }
        write!(f, ")")?;
        if let Some(id) = &self.id {
            write!(
                f,
                ".property(T.id, {})",
                crate::value::literal::rhai_string(id)
            )?;
        }
        Ok(())
    }
}

impl AddElementStep for StepAddV {
    fn set_id(&mut self, id: CompactString) {
        self.id = Some(id);
    }

    fn set_label(&mut self, label: CompactString) -> bool {
        self.args = Some(vec![label.to_string()]);
        true
    }

    fn fold_property(&mut self, key: CompactString, value: ElementProperty) {
        self.properties.insert(key, value);
    }
}

impl<'g, S: GraphStorage + 'g> GraphTraversalSource<'g, S> {
    /// Adds a vertex with the given label; chain property() to set its properties.
    pub fn add_v<T: Into<ArgStrings>>(self, args: T) -> Self {
        let args = match args.into() {
            ArgStrings::None => None,
            ArgStrings::String(v) => Some(vec![v]),
            // A list is the intended way to create a multi-label vertex (D8) — no longer an
            // error shape.
            ArgStrings::List(v) => Some(v),
        };

        let step = GraphStep::SideEffectMut(
            "add_v",
            Box::new(StepAddV {
                args,
                id: None,
                properties: PropertyMap::default(),
            }),
        );
        self.push_step(step)
    }
}

impl __ {
    /// Adds a vertex with the given label; chain property() to set its properties. Starts an
    /// anonymous traversal (`__.add_v()`).
    pub fn add_v<'g, S: GraphStorage + 'g, T: Into<ArgStrings>>(
        labels: T,
    ) -> AnonymousTraversal<'g, S> {
        AnonymousTraversal::new().add_v(labels)
    }
}

impl<'g, S: GraphStorage + 'g> AnonymousTraversal<'g, S> {
    /// Adds a vertex with the given label; chain property() to set its properties.
    pub fn add_v<T: Into<ArgStrings>>(self, args: T) -> Self {
        let args = match args.into() {
            ArgStrings::None => None,
            ArgStrings::String(v) => Some(vec![v]),
            ArgStrings::List(v) => Some(v),
        };
        let step = GraphStep::SideEffectMut(
            "add_v",
            Box::new(StepAddV {
                args,
                id: None,
                properties: PropertyMap::default(),
            }),
        );
        self.push_step(step)
    }
}

impl<'g, S: GraphStorage + 'g> GraphStepSideEffectMut<'g, S> for StepAddV {
    fn static_labels(&self) -> Vec<&str> {
        self.args.iter().flatten().map(String::as_str).collect()
    }

    #[inline]
    fn process(
        &self,
        context: &mut TraverserContext<'_, S>,
        source: Option<Traverser<S>>,
    ) -> TraverserResult<Vec<Traverser<S>>> {
        let labels = self
            .args
            .clone()
            .unwrap_or_default()
            .into_iter()
            .map(CompactString::from)
            .collect();
        let node_index =
            context
                .storage
                .add_vertex(self.id.clone(), labels, self.properties.clone())?;
        match source {
            // Derived from the incoming traverser (TinkerPop `split`): its path, bulk and sack.
            Some(source) => Ok(vec![source.split(TraverserValue::Vertex(node_index))]),
            None => Ok(vec![Traverser::start(
                context,
                TraverserValue::Vertex(node_index),
            )]),
        }
    }

    fn as_add_element_mut(&mut self) -> Option<&mut dyn AddElementStep> {
        Some(self)
    }

    fn clone_box(&self) -> Box<dyn GraphStepSideEffectMut<'g, S> + 'g> {
        Box::new(self.clone())
    }
}

/// `addV(traversal)`: the label of the new vertex is the first result of a child traversal, run
/// on the incoming traverser (on a `null` seed for the start form `g.addV(..)`), TinkerPop's
/// `AddVertexStep` with a label traversal. The result must be a string; no result or another
/// value is a cast error.
struct StepAddVBy<'g, S: GraphStorage + 'g> {
    label: AnonymousTraversal<'g, S>,
    /// The user-supplied id from a folded `property(T.id, v)`.
    id: Option<CompactString>,
    /// The properties folded in by the `add_property_fold` rule.
    properties: PropertyMap,
}

impl<'g, S: GraphStorage + 'g> Clone for StepAddVBy<'g, S> {
    fn clone(&self) -> Self {
        Self {
            label: self.label.clone(),
            id: self.id.clone(),
            properties: self.properties.clone(),
        }
    }
}

impl<'g, S: GraphStorage + 'g> fmt::Display for StepAddVBy<'g, S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "add_v({}", self.label)?;
        if !self.properties.is_empty() {
            let keys: Vec<&str> = self.properties.keys().map(|k| k.as_str()).collect();
            write!(
                f,
                ", properties: {}",
                crate::value::literal::rhai_string_array(&keys)
            )?;
        }
        write!(f, ")")?;
        if let Some(id) = &self.id {
            write!(
                f,
                ".property(T.id, {})",
                crate::value::literal::rhai_string(id)
            )?;
        }
        Ok(())
    }
}

impl<'g, S: GraphStorage + 'g> AddElementStep for StepAddVBy<'g, S> {
    fn set_id(&mut self, id: CompactString) {
        self.id = Some(id);
    }

    /// The label comes from the traversal; a `property(T.label, ..)` stays a separate step.
    fn set_label(&mut self, _label: CompactString) -> bool {
        false
    }

    fn fold_property(&mut self, key: CompactString, value: ElementProperty) {
        self.properties.insert(key, value);
    }
}

fn add_v_by_step<'g, S: GraphStorage + 'g>(label: AnonymousTraversal<'g, S>) -> GraphStep<'g, S> {
    GraphStep::SideEffectMut(
        "add_v",
        Box::new(StepAddVBy {
            label,
            id: None,
            properties: PropertyMap::default(),
        }),
    )
}

impl<'g, S: GraphStorage + 'g> GraphTraversalSource<'g, S> {
    /// `addV(traversal)`: adds a vertex whose label is the first result of `label`, run on the
    /// incoming traverser (on a `null` seed when the step starts the traversal); it must be a
    /// string.
    ///
    /// ```rust
    /// use graphersal::prelude::*;
    ///
    /// let mut graph = TraversalGraph::tinkerpop_modern();
    /// let label = graph
    ///     .traversal_mut()
    ///     .v("1")
    ///     .add_v_by(__::label())
    ///     .label()
    ///     .next()
    ///     .unwrap();
    /// assert_eq!(label.as_ref().and_then(|l| l.as_string()), Some("person"));
    /// ```
    pub fn add_v_by(self, label: AnonymousTraversal<'g, S>) -> Self {
        self.push_step(add_v_by_step(label))
    }
}

impl __ {
    /// `__.addV(traversal)`; see [`GraphTraversalSource::add_v_by`].
    pub fn add_v_by<'g, S: GraphStorage + 'g>(
        label: AnonymousTraversal<'g, S>,
    ) -> AnonymousTraversal<'g, S> {
        AnonymousTraversal::new().add_v_by(label)
    }
}

impl<'g, S: GraphStorage + 'g> AnonymousTraversal<'g, S> {
    /// `addV(traversal)` inside a child traversal; see [`GraphTraversalSource::add_v_by`].
    pub fn add_v_by(self, label: AnonymousTraversal<'g, S>) -> Self {
        self.push_step(add_v_by_step(label))
    }
}

impl<'g, S: GraphStorage + 'g> GraphStepSideEffectMut<'g, S> for StepAddVBy<'g, S> {
    fn process(
        &self,
        context: &mut TraverserContext<'_, S>,
        source: Option<Traverser<S>>,
    ) -> TraverserResult<Vec<Traverser<S>>> {
        let seed;
        let parent: &Traverser<S> = match &source {
            Some(traverser) => traverser,
            None => {
                seed = Traverser::start(
                    context,
                    TraverserValue::Computed(ElementProperty::Null, None),
                );
                &seed
            }
        };
        let label = match self.label.first(context, parent)? {
            Some(found) => match found.value.into_node_property(context.storage)? {
                ElementProperty::String(text) => text,
                other => {
                    return Err(Box::new(TraverserError::cast_exception_str(
                        &["string"],
                        crate::graph::schema::value_type_name(&other).to_string(),
                    )));
                }
            },
            None => {
                return Err(Box::new(TraverserError::cast_exception_str(
                    &["string"],
                    "null".to_string(),
                )));
            }
        };
        let node_index =
            context
                .storage
                .add_vertex(self.id.clone(), vec![label], self.properties.clone())?;
        match source {
            // Derived from the incoming traverser: its path, bulk and sack.
            Some(source) => Ok(vec![source.split(TraverserValue::Vertex(node_index))]),
            // Generated: the start form.
            None => Ok(vec![Traverser::start(
                context,
                TraverserValue::Vertex(node_index),
            )]),
        }
    }

    fn child_traversals_mut(&mut self) -> Vec<&mut AnonymousTraversal<'g, S>> {
        vec![&mut self.label]
    }

    fn analyze_nested_paths(
        &mut self,
        analysis: &crate::traversal::optimizer::path_analysis::PathAnalysis,
        _downstream: &crate::traversal::optimizer::path_analysis::PathRequirement,
    ) -> crate::traversal::optimizer::path_analysis::PathRequirement {
        // The label traversal runs on the incoming traverser; only its first result is used.
        self.label.analyze_paths(
            analysis,
            crate::traversal::optimizer::path_analysis::PathRequirement::None,
        )
    }

    fn as_add_element_mut(&mut self) -> Option<&mut dyn AddElementStep> {
        Some(self)
    }

    fn clone_box(&self) -> Box<dyn GraphStepSideEffectMut<'g, S> + 'g> {
        Box::new(self.clone())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn add_v_by_traversal_label() {
        let mut graph = TraversalGraph::tinkerpop_modern();
        let label = graph
            .traversal_mut()
            .add_v_by(__::constant("prefix_").concat_traversal(vec![__::v("1").label()]))
            .label()
            .next()
            .unwrap();
        assert_eq!(
            label.as_ref().and_then(|l| l.as_string()),
            Some("prefix_person")
        );
    }

    #[test]
    fn add_v_by_non_string_label_is_a_cast_error() {
        let mut graph = TraversalGraph::tinkerpop_modern();
        let err = graph
            .traversal_mut()
            .add_v_by(__::constant(1))
            .next()
            .expect_err("a number is not a label");
        let report = crate::error::format_diagnostic(&err);
        assert!(report.contains("string"), "{report}");
    }

    #[test]
    fn start_none() {
        let mut graph = TraversalGraph::new();
        let result = graph.traversal_mut().add_v(None).next().unwrap().unwrap();
        match result {
            ElementProperty::Vertex(vertex) => {
                assert_eq!(vertex.get("id"), Some(&ElementProperty::String("1".into())));
                assert_eq!(vertex.get("label"), None);
            }
            _ => panic!(),
        }
    }

    #[test]
    fn start_label() {
        let mut graph = TraversalGraph::new();
        let result = graph
            .traversal_mut()
            .add_v("product")
            .next()
            .unwrap()
            .unwrap();
        match result {
            ElementProperty::Vertex(vertex) => {
                assert_eq!(vertex.get("id"), Some(&ElementProperty::String("1".into())));
                assert_eq!(
                    vertex.get("label"),
                    Some(&ElementProperty::String("product".into()))
                );
            }
            _ => panic!(),
        }
    }

    #[test]
    fn second_none() {
        let mut graph = TraversalGraph::new();
        let result = graph
            .traversal_mut()
            .add_v(None)
            .add_v(None)
            .next()
            .unwrap()
            .unwrap();
        match result {
            ElementProperty::Vertex(vertex) => {
                assert_eq!(vertex.get("id"), Some(&ElementProperty::String("2".into())));
                assert_eq!(vertex.get("label"), None);
            }
            _ => panic!(),
        }
    }

    #[test]
    fn second_label() {
        let mut graph = TraversalGraph::new();
        let result = graph
            .traversal_mut()
            .add_v("quote")
            .add_v("product")
            .next()
            .unwrap()
            .unwrap();
        match result {
            ElementProperty::Vertex(vertex) => {
                assert_eq!(vertex.get("id"), Some(&ElementProperty::String("2".into())));
                assert_eq!(
                    vertex.get("label"),
                    Some(&ElementProperty::String("product".into()))
                );
            }
            _ => panic!(),
        }
    }

    #[test]
    fn profile() {
        let mut graph = TraversalGraph::new();
        let result = graph
            .traversal_mut()
            .add_v("quote")
            .add_v("product")
            .profile()
            .unwrap();
        assert!(result.to_string().contains("add_v("));
    }

    #[test]
    fn list_label_creates_a_multi_label_vertex() {
        // A list argument is now the intended way to create a multi-label vertex (D8), not an
        // error shape.
        let mut graph = TraversalGraph::new();
        let result = graph
            .traversal_mut()
            .add_v(vec!["Person", "Admin"])
            .next()
            .unwrap()
            .unwrap();
        match result {
            ElementProperty::Vertex(vertex) => {
                assert_eq!(vertex.get("id"), Some(&ElementProperty::String("1".into())));
                // elementMap()'s "label" key stays single-valued: the primary (first) label.
                assert_eq!(
                    vertex.get("label"),
                    Some(&ElementProperty::String("Person".into()))
                );
            }
            _ => panic!(),
        }
        let idx = GraphStorage::get_vertex_by_id(&graph, "1").unwrap();
        let labels = GraphStorage::vertex_labels(&graph, idx);
        assert_eq!(
            labels,
            &[CompactString::new("Person"), CompactString::new("Admin")][..]
        );
    }
}