interstellar 0.2.0

A high-performance graph database with Gremlin-style traversals and GQL query language
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
//! Builder wrappers for WASM bindings.
//!
//! Provides JavaScript-friendly builder patterns for steps like order(), group(), etc.
//! These wrap the WASM Traversal and accumulate configuration before building the final step.

use std::sync::Arc;

use wasm_bindgen::prelude::*;
use wasm_bindgen::JsError;

use crate::storage::cow::Graph as InnerGraph;
use crate::traversal::aggregate::{GroupKey, GroupValue};
use crate::traversal::repeat::RepeatConfig;
use crate::traversal::transform::functional::Projection;
use crate::traversal::transform::order::{Order, OrderKey};
use crate::value::Value;
use crate::wasm::traversal::{Traversal, TraversalType};
use crate::wasm::types::js_to_u64;

// =============================================================================
// OrderBuilder
// =============================================================================

/// Builder for order() step configuration.
///
/// @example
/// ```typescript
/// graph.V()
///     .order()
///     .byKeyAsc('name')
///     .byKeyDesc('age')
///     .build()
///     .toList();
/// ```
#[wasm_bindgen]
pub struct OrderBuilder {
    graph: Arc<InnerGraph>,
    steps: Vec<Box<dyn crate::traversal::DynStep>>,
    output_type: TraversalType,
    keys: Vec<OrderKey>,
}

impl OrderBuilder {
    pub(crate) fn new(traversal: Traversal) -> Self {
        Self {
            graph: traversal.graph.clone(),
            steps: traversal.steps,
            output_type: traversal.output_type,
            keys: Vec::new(),
        }
    }
}

#[wasm_bindgen]
impl OrderBuilder {
    /// Order by natural value (ascending).
    #[wasm_bindgen(js_name = "byAsc")]
    pub fn by_asc(mut self) -> OrderBuilder {
        self.keys.push(OrderKey::Natural(Order::Asc));
        self
    }

    /// Order by natural value (descending).
    #[wasm_bindgen(js_name = "byDesc")]
    pub fn by_desc(mut self) -> OrderBuilder {
        self.keys.push(OrderKey::Natural(Order::Desc));
        self
    }

    /// Order by a property key (ascending).
    ///
    /// @param key - Property name
    #[wasm_bindgen(js_name = "byKeyAsc")]
    pub fn by_key_asc(mut self, key: &str) -> OrderBuilder {
        self.keys
            .push(OrderKey::Property(key.to_string(), Order::Asc));
        self
    }

    /// Order by a property key (descending).
    ///
    /// @param key - Property name
    #[wasm_bindgen(js_name = "byKeyDesc")]
    pub fn by_key_desc(mut self, key: &str) -> OrderBuilder {
        self.keys
            .push(OrderKey::Property(key.to_string(), Order::Desc));
        self
    }

    /// Order by the result of a traversal (ascending).
    ///
    /// @param traversal - Anonymous traversal
    #[wasm_bindgen(js_name = "byTraversalAsc")]
    pub fn by_traversal_asc(mut self, traversal: Traversal) -> OrderBuilder {
        let core_traversal = traversal.into_core_traversal();
        self.keys
            .push(OrderKey::Traversal(core_traversal, Order::Asc));
        self
    }

    /// Order by the result of a traversal (descending).
    ///
    /// @param traversal - Anonymous traversal
    #[wasm_bindgen(js_name = "byTraversalDesc")]
    pub fn by_traversal_desc(mut self, traversal: Traversal) -> OrderBuilder {
        let core_traversal = traversal.into_core_traversal();
        self.keys
            .push(OrderKey::Traversal(core_traversal, Order::Desc));
        self
    }

    /// Finalize the order step and return to traversal.
    pub fn build(mut self) -> Traversal {
        // Default to ascending natural order if no keys specified
        if self.keys.is_empty() {
            self.keys.push(OrderKey::Natural(Order::Asc));
        }

        let step = crate::traversal::OrderStep::with_keys(self.keys);
        self.steps.push(Box::new(step));

        Traversal {
            graph: self.graph,
            source: crate::wasm::traversal::TraversalSource::Anonymous, // Will be fixed by caller
            steps: self.steps,
            output_type: self.output_type,
        }
    }
}

// =============================================================================
// ProjectBuilder
// =============================================================================

/// Builder for project() step configuration.
///
/// @example
/// ```typescript
/// graph.V()
///     .project('name', 'friendCount')
///     .byKey('name', 'name')
///     .byTraversal('friendCount', __.out('knows').count())
///     .build()
///     .toList();
/// ```
#[wasm_bindgen]
pub struct ProjectBuilder {
    graph: Arc<InnerGraph>,
    steps: Vec<Box<dyn crate::traversal::DynStep>>,
    #[allow(dead_code)]
    output_type: TraversalType,
    keys: Vec<String>,
    projections: Vec<Projection>,
}

impl ProjectBuilder {
    pub(crate) fn new(traversal: Traversal, keys: Vec<String>) -> Self {
        Self {
            graph: traversal.graph.clone(),
            steps: traversal.steps,
            output_type: traversal.output_type,
            keys,
            projections: Vec::new(),
        }
    }
}

#[wasm_bindgen]
impl ProjectBuilder {
    /// Project a key using a property value.
    ///
    /// @param propertyKey - Property to extract
    #[wasm_bindgen(js_name = "byKey")]
    pub fn by_key(mut self, property_key: &str) -> ProjectBuilder {
        self.projections
            .push(Projection::Key(property_key.to_string()));
        self
    }

    /// Project a key using a traversal result.
    ///
    /// @param traversal - Anonymous traversal
    #[wasm_bindgen(js_name = "byTraversal")]
    pub fn by_traversal(mut self, traversal: Traversal) -> ProjectBuilder {
        let core_traversal = traversal.into_core_traversal();
        self.projections.push(Projection::Traversal(core_traversal));
        self
    }

    /// Finalize the project step and return to traversal.
    pub fn build(mut self) -> Traversal {
        // Pad projections with identity if not enough were specified
        while self.projections.len() < self.keys.len() {
            // Default to identity - not directly available, use Key("") as placeholder
            // Better: we should default to extracting the key with same name
            let key = &self.keys[self.projections.len()];
            self.projections.push(Projection::Key(key.clone()));
        }

        let step = crate::traversal::ProjectStep::new(self.keys, self.projections);
        self.steps.push(Box::new(step));

        Traversal {
            graph: self.graph,
            source: crate::wasm::traversal::TraversalSource::Anonymous,
            steps: self.steps,
            output_type: TraversalType::Value,
        }
    }
}

// =============================================================================
// GroupBuilder
// =============================================================================

/// Builder for group() step configuration.
///
/// @example
/// ```typescript
/// graph.V()
///     .group()
///     .byKey('age')
///     .valuesByTraversal(__.values('name'))
///     .build()
///     .toList();
/// ```
#[wasm_bindgen]
pub struct GroupBuilder {
    graph: Arc<InnerGraph>,
    steps: Vec<Box<dyn crate::traversal::DynStep>>,
    #[allow(dead_code)]
    output_type: TraversalType,
    key_selector: Option<GroupKey>,
    value_collector: Option<GroupValue>,
}

impl GroupBuilder {
    pub(crate) fn new(traversal: Traversal) -> Self {
        Self {
            graph: traversal.graph.clone(),
            steps: traversal.steps,
            output_type: traversal.output_type,
            key_selector: None,
            value_collector: None,
        }
    }
}

#[wasm_bindgen]
impl GroupBuilder {
    /// Group by element label.
    #[wasm_bindgen(js_name = "byLabel")]
    pub fn by_label(mut self) -> GroupBuilder {
        self.key_selector = Some(GroupKey::Label);
        self
    }

    /// Group by a property key.
    ///
    /// @param key - Property name
    #[wasm_bindgen(js_name = "byKey")]
    pub fn by_key(mut self, key: &str) -> GroupBuilder {
        self.key_selector = Some(GroupKey::Property(key.to_string()));
        self
    }

    /// Group by the result of a traversal.
    ///
    /// @param traversal - Anonymous traversal
    #[wasm_bindgen(js_name = "byTraversal")]
    pub fn by_traversal(mut self, traversal: Traversal) -> GroupBuilder {
        let core_traversal = traversal.into_core_traversal();
        self.key_selector = Some(GroupKey::Traversal(Box::new(core_traversal)));
        self
    }

    /// Aggregate values using a traversal.
    ///
    /// @param traversal - Anonymous traversal for values
    #[wasm_bindgen(js_name = "valuesByTraversal")]
    pub fn values_by_traversal(mut self, traversal: Traversal) -> GroupBuilder {
        let core_traversal = traversal.into_core_traversal();
        self.value_collector = Some(GroupValue::Traversal(Box::new(core_traversal)));
        self
    }

    /// Aggregate values using fold (collect into list).
    #[wasm_bindgen(js_name = "valuesFold")]
    pub fn values_fold(mut self) -> GroupBuilder {
        // Identity means the value itself is collected (which fold then collects into list)
        self.value_collector = Some(GroupValue::Identity);
        self
    }

    /// Aggregate values by extracting a property.
    ///
    /// @param key - Property name
    #[wasm_bindgen(js_name = "valuesByKey")]
    pub fn values_by_key(mut self, key: &str) -> GroupBuilder {
        self.value_collector = Some(GroupValue::Property(key.to_string()));
        self
    }

    /// Finalize the group step and return to traversal.
    pub fn build(mut self) -> Traversal {
        let key_selector = self.key_selector.unwrap_or(GroupKey::Label);
        let value_collector = self.value_collector.unwrap_or(GroupValue::Identity);

        let step = crate::traversal::GroupStep::with_selectors(key_selector, value_collector);
        self.steps.push(Box::new(step));

        Traversal {
            graph: self.graph,
            source: crate::wasm::traversal::TraversalSource::Anonymous,
            steps: self.steps,
            output_type: TraversalType::Value,
        }
    }
}

// =============================================================================
// GroupCountBuilder
// =============================================================================

/// Builder for groupCount() step configuration.
///
/// @example
/// ```typescript
/// graph.V()
///     .groupCount()
///     .byKey('age')
///     .build()
///     .toList();
/// ```
#[wasm_bindgen]
pub struct GroupCountBuilder {
    graph: Arc<InnerGraph>,
    steps: Vec<Box<dyn crate::traversal::DynStep>>,
    #[allow(dead_code)]
    output_type: TraversalType,
    key_selector: Option<GroupKey>,
}

impl GroupCountBuilder {
    pub(crate) fn new(traversal: Traversal) -> Self {
        Self {
            graph: traversal.graph.clone(),
            steps: traversal.steps,
            output_type: traversal.output_type,
            key_selector: None,
        }
    }
}

#[wasm_bindgen]
impl GroupCountBuilder {
    /// Count by element label.
    #[wasm_bindgen(js_name = "byLabel")]
    pub fn by_label(mut self) -> GroupCountBuilder {
        self.key_selector = Some(GroupKey::Label);
        self
    }

    /// Count by a property key.
    ///
    /// @param key - Property name
    #[wasm_bindgen(js_name = "byKey")]
    pub fn by_key(mut self, key: &str) -> GroupCountBuilder {
        self.key_selector = Some(GroupKey::Property(key.to_string()));
        self
    }

    /// Count by the result of a traversal.
    ///
    /// @param traversal - Anonymous traversal
    #[wasm_bindgen(js_name = "byTraversal")]
    pub fn by_traversal(mut self, traversal: Traversal) -> GroupCountBuilder {
        let core_traversal = traversal.into_core_traversal();
        self.key_selector = Some(GroupKey::Traversal(Box::new(core_traversal)));
        self
    }

    /// Finalize the groupCount step and return to traversal.
    pub fn build(mut self) -> Traversal {
        let key_selector = self.key_selector.unwrap_or(GroupKey::Label);

        let step = crate::traversal::GroupCountStep::new(key_selector);
        self.steps.push(Box::new(step));

        Traversal {
            graph: self.graph,
            source: crate::wasm::traversal::TraversalSource::Anonymous,
            steps: self.steps,
            output_type: TraversalType::Value,
        }
    }
}

// =============================================================================
// RepeatBuilder
// =============================================================================

/// Builder for repeat() step configuration.
///
/// @example
/// ```typescript
/// graph.V_(startId)
///     .repeat(__.out('knows'))
///     .times(3n)
///     .build()
///     .toList();
/// ```
#[wasm_bindgen]
pub struct RepeatBuilder {
    graph: Arc<InnerGraph>,
    steps: Vec<Box<dyn crate::traversal::DynStep>>,
    output_type: TraversalType,
    sub_traversal: crate::traversal::Traversal<Value, Value>,
    config: RepeatConfig,
}

impl RepeatBuilder {
    pub(crate) fn new(traversal: Traversal, sub: Traversal) -> Self {
        Self {
            graph: traversal.graph.clone(),
            steps: traversal.steps,
            output_type: traversal.output_type,
            sub_traversal: sub.into_core_traversal(),
            config: RepeatConfig::new(),
        }
    }
}

#[wasm_bindgen]
impl RepeatBuilder {
    /// Repeat a fixed number of times.
    ///
    /// @param n - Number of iterations
    pub fn times(mut self, n: JsValue) -> Result<RepeatBuilder, JsError> {
        let num = js_to_u64(n)?;
        self.config = self.config.with_times(num as usize);
        Ok(self)
    }

    /// Repeat until a condition is met.
    ///
    /// @param condition - Anonymous traversal that determines when to stop
    pub fn until(mut self, condition: Traversal) -> RepeatBuilder {
        let core_traversal = condition.into_core_traversal();
        self.config = self.config.with_until(core_traversal);
        self
    }

    /// Emit elements during iteration.
    pub fn emit(mut self) -> RepeatBuilder {
        self.config = self.config.with_emit();
        self
    }

    /// Emit elements that match a condition.
    ///
    /// @param condition - Anonymous traversal that determines when to emit
    #[wasm_bindgen(js_name = "emitIf")]
    pub fn emit_if(mut self, condition: Traversal) -> RepeatBuilder {
        let core_traversal = condition.into_core_traversal();
        self.config = self.config.with_emit_if(core_traversal);
        self
    }

    /// Finalize the repeat step and return to traversal.
    pub fn build(mut self) -> Traversal {
        let step = crate::traversal::RepeatStep::with_config(self.sub_traversal, self.config);
        self.steps.push(Box::new(step));

        Traversal {
            graph: self.graph,
            source: crate::wasm::traversal::TraversalSource::Anonymous,
            steps: self.steps,
            output_type: self.output_type,
        }
    }
}