kitedb 0.2.15

High-performance embedded graph database
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! Query Builders
//!
//! Fluent builders for insert, update, delete, link, and unlink operations.
//!
//! Ported from src/api/builders.ts

use crate::error::{KiteError, Result};
use crate::types::{ETypeId, NodeId, PropKeyId, PropValue};
use std::collections::HashMap;

// ============================================================================
// Node Reference
// ============================================================================

/// A reference to a node with its ID and key
#[derive(Debug, Clone)]
pub struct NodeRef {
  /// Node ID
  id: NodeId,
  /// Node key (may be empty)
  key: String,
  /// Node properties (cached)
  props: HashMap<String, PropValue>,
}

impl NodeRef {
  /// Create a new node reference
  pub fn new(id: NodeId, key: impl Into<String>) -> Self {
    Self {
      id,
      key: key.into(),
      props: HashMap::new(),
    }
  }

  /// Create a node reference with properties
  pub fn with_props(id: NodeId, key: impl Into<String>, props: HashMap<String, PropValue>) -> Self {
    Self {
      id,
      key: key.into(),
      props,
    }
  }

  pub fn id(&self) -> NodeId {
    self.id
  }

  pub fn key(&self) -> &str {
    &self.key
  }

  pub fn props(&self) -> &HashMap<String, PropValue> {
    &self.props
  }

  pub fn into_parts(self) -> (NodeId, String, HashMap<String, PropValue>) {
    (self.id, self.key, self.props)
  }

  /// Get a property value
  pub fn prop(&self, name: &str) -> Option<&PropValue> {
    self.props.get(name)
  }
}

// ============================================================================
// Insert Builder
// ============================================================================

/// Builder for insert operations
pub struct InsertBuilder<'a, F, R>
where
  F: FnMut(InsertData) -> R,
{
  /// Function to execute the insert
  executor: &'a mut F,
  /// Node type name
  _node_type: String,
}

/// Data for insert operation
#[derive(Debug, Clone)]
pub struct InsertData {
  /// Node key (optional)
  pub key: Option<String>,
  /// Properties to set
  pub props: HashMap<PropKeyId, PropValue>,
}

impl InsertData {
  pub fn new() -> Self {
    Self {
      key: None,
      props: HashMap::new(),
    }
  }

  pub fn with_key(mut self, key: impl Into<String>) -> Self {
    self.key = Some(key.into());
    self
  }

  pub fn with_prop(mut self, key_id: PropKeyId, value: PropValue) -> Self {
    self.props.insert(key_id, value);
    self
  }
}

impl Default for InsertData {
  fn default() -> Self {
    Self::new()
  }
}

impl<'a, F, R> InsertBuilder<'a, F, R>
where
  F: FnMut(InsertData) -> R,
{
  /// Create a new insert builder
  pub fn new(node_type: impl Into<String>, executor: &'a mut F) -> Self {
    Self {
      executor,
      _node_type: node_type.into(),
    }
  }

  /// Execute the insert with the given data
  pub fn values(self, data: InsertData) -> R {
    (self.executor)(data)
  }
}

// ============================================================================
// Update Builder
// ============================================================================

/// Builder for update operations
pub struct UpdateBuilder<'a, F, R>
where
  F: FnMut(NodeId, HashMap<PropKeyId, Option<PropValue>>) -> R,
{
  /// Function to execute the update
  executor: &'a mut F,
  /// Node to update
  node_id: Option<NodeId>,
  /// Updates to apply (None value = delete property)
  updates: HashMap<PropKeyId, Option<PropValue>>,
}

impl<'a, F, R> UpdateBuilder<'a, F, R>
where
  F: FnMut(NodeId, HashMap<PropKeyId, Option<PropValue>>) -> R,
{
  /// Create a new update builder
  pub fn new(executor: &'a mut F) -> Self {
    Self {
      executor,
      node_id: None,
      updates: HashMap::new(),
    }
  }

  /// Set the target node by ID
  pub fn where_id(mut self, node_id: NodeId) -> Self {
    self.node_id = Some(node_id);
    self
  }

  /// Set a property value
  pub fn set(mut self, prop_key_id: PropKeyId, value: PropValue) -> Self {
    self.updates.insert(prop_key_id, Some(value));
    self
  }

  /// Delete a property
  pub fn unset(mut self, prop_key_id: PropKeyId) -> Self {
    self.updates.insert(prop_key_id, None);
    self
  }

  /// Execute the update
  pub fn execute(self) -> Result<R> {
    let node_id = self.node_id.ok_or_else(|| {
      KiteError::InvalidQuery("Update requires a node ID (use where_id())".into())
    })?;
    Ok((self.executor)(node_id, self.updates))
  }
}

// ============================================================================
// Delete Builder
// ============================================================================

/// Builder for delete operations
pub struct DeleteBuilder<'a, F, R>
where
  F: FnMut(NodeId) -> R,
{
  /// Function to execute the delete
  executor: &'a mut F,
  /// Node to delete
  node_id: Option<NodeId>,
}

impl<'a, F, R> DeleteBuilder<'a, F, R>
where
  F: FnMut(NodeId) -> R,
{
  /// Create a new delete builder
  pub fn new(executor: &'a mut F) -> Self {
    Self {
      executor,
      node_id: None,
    }
  }

  /// Set the target node by ID
  pub fn where_id(mut self, node_id: NodeId) -> Self {
    self.node_id = Some(node_id);
    self
  }

  /// Execute the delete
  pub fn execute(self) -> Result<R> {
    let node_id = self.node_id.ok_or_else(|| {
      KiteError::InvalidQuery("Delete requires a node ID (use where_id())".into())
    })?;
    Ok((self.executor)(node_id))
  }
}

// ============================================================================
// Link Builder
// ============================================================================

/// Builder for creating edges (links)
pub struct LinkBuilder<'a, F, R>
where
  F: FnMut(NodeId, ETypeId, NodeId, HashMap<PropKeyId, PropValue>) -> R,
{
  /// Function to execute the link
  executor: &'a mut F,
  /// Source node
  src: NodeId,
  /// Edge type
  etype: ETypeId,
  /// Destination node
  dst: Option<NodeId>,
  /// Edge properties
  props: HashMap<PropKeyId, PropValue>,
}

impl<'a, F, R> LinkBuilder<'a, F, R>
where
  F: FnMut(NodeId, ETypeId, NodeId, HashMap<PropKeyId, PropValue>) -> R,
{
  /// Create a new link builder
  pub fn new(src: NodeId, etype: ETypeId, executor: &'a mut F) -> Self {
    Self {
      executor,
      src,
      etype,
      dst: None,
      props: HashMap::new(),
    }
  }

  /// Set the destination node
  pub fn to(mut self, dst: NodeId) -> Self {
    self.dst = Some(dst);
    self
  }

  /// Set an edge property
  pub fn with_prop(mut self, prop_key_id: PropKeyId, value: PropValue) -> Self {
    self.props.insert(prop_key_id, value);
    self
  }

  /// Execute the link
  pub fn execute(self) -> Result<R> {
    let dst = self
      .dst
      .ok_or_else(|| KiteError::InvalidQuery("Link requires a destination (use to())".into()))?;
    Ok((self.executor)(self.src, self.etype, dst, self.props))
  }
}

// ============================================================================
// Unlink Builder
// ============================================================================

/// Builder for deleting edges (unlinks)
pub struct UnlinkBuilder<'a, F, R>
where
  F: FnMut(NodeId, ETypeId, NodeId) -> R,
{
  /// Function to execute the unlink
  executor: &'a mut F,
  /// Source node
  src: NodeId,
  /// Edge type
  etype: ETypeId,
  /// Destination node
  dst: Option<NodeId>,
}

impl<'a, F, R> UnlinkBuilder<'a, F, R>
where
  F: FnMut(NodeId, ETypeId, NodeId) -> R,
{
  /// Create a new unlink builder
  pub fn new(src: NodeId, etype: ETypeId, executor: &'a mut F) -> Self {
    Self {
      executor,
      src,
      etype,
      dst: None,
    }
  }

  /// Set the destination node
  pub fn from_node(mut self, dst: NodeId) -> Self {
    self.dst = Some(dst);
    self
  }

  /// Execute the unlink
  pub fn execute(self) -> Result<R> {
    let dst = self.dst.ok_or_else(|| {
      KiteError::InvalidQuery("Unlink requires a destination (use from_node())".into())
    })?;
    Ok((self.executor)(self.src, self.etype, dst))
  }
}

// ============================================================================
// Update Edge Builder
// ============================================================================

/// Builder for updating edge properties
pub struct UpdateEdgeBuilder<'a, F, R>
where
  F: FnMut(NodeId, ETypeId, NodeId, HashMap<PropKeyId, Option<PropValue>>) -> R,
{
  /// Function to execute the update
  executor: &'a mut F,
  /// Source node
  src: NodeId,
  /// Edge type
  etype: ETypeId,
  /// Destination node
  dst: NodeId,
  /// Updates to apply
  updates: HashMap<PropKeyId, Option<PropValue>>,
}

impl<'a, F, R> UpdateEdgeBuilder<'a, F, R>
where
  F: FnMut(NodeId, ETypeId, NodeId, HashMap<PropKeyId, Option<PropValue>>) -> R,
{
  /// Create a new update edge builder
  pub fn new(src: NodeId, etype: ETypeId, dst: NodeId, executor: &'a mut F) -> Self {
    Self {
      executor,
      src,
      etype,
      dst,
      updates: HashMap::new(),
    }
  }

  /// Set an edge property
  pub fn set(mut self, prop_key_id: PropKeyId, value: PropValue) -> Self {
    self.updates.insert(prop_key_id, Some(value));
    self
  }

  /// Delete an edge property
  pub fn unset(mut self, prop_key_id: PropKeyId) -> Self {
    self.updates.insert(prop_key_id, None);
    self
  }

  /// Execute the update
  pub fn execute(self) -> R {
    (self.executor)(self.src, self.etype, self.dst, self.updates)
  }
}

// ============================================================================
// Batch Operations
// ============================================================================

/// A batch operation that can be executed in a transaction
#[derive(Debug, Clone)]
pub enum BatchOp {
  /// Insert a node
  Insert(InsertData),
  /// Update a node
  Update {
    node_id: NodeId,
    updates: HashMap<PropKeyId, Option<PropValue>>,
  },
  /// Delete a node
  Delete { node_id: NodeId },
  /// Create an edge
  Link {
    src: NodeId,
    etype: ETypeId,
    dst: NodeId,
    props: HashMap<PropKeyId, PropValue>,
  },
  /// Delete an edge
  Unlink {
    src: NodeId,
    etype: ETypeId,
    dst: NodeId,
  },
  /// Update edge properties
  UpdateEdge {
    src: NodeId,
    etype: ETypeId,
    dst: NodeId,
    updates: HashMap<PropKeyId, Option<PropValue>>,
  },
}

/// Collect batch operations for execution in a single transaction
#[derive(Debug, Default)]
pub struct BatchBuilder {
  ops: Vec<BatchOp>,
}

impl BatchBuilder {
  pub fn new() -> Self {
    Self { ops: Vec::new() }
  }

  /// Add an insert operation
  pub fn insert(mut self, data: InsertData) -> Self {
    self.ops.push(BatchOp::Insert(data));
    self
  }

  /// Add an update operation
  pub fn update(mut self, node_id: NodeId, updates: HashMap<PropKeyId, Option<PropValue>>) -> Self {
    self.ops.push(BatchOp::Update { node_id, updates });
    self
  }

  /// Add a delete operation
  pub fn delete(mut self, node_id: NodeId) -> Self {
    self.ops.push(BatchOp::Delete { node_id });
    self
  }

  /// Add a link operation
  pub fn link(mut self, src: NodeId, etype: ETypeId, dst: NodeId) -> Self {
    self.ops.push(BatchOp::Link {
      src,
      etype,
      dst,
      props: HashMap::new(),
    });
    self
  }

  /// Add a link operation with properties
  pub fn link_with_props(
    mut self,
    src: NodeId,
    etype: ETypeId,
    dst: NodeId,
    props: HashMap<PropKeyId, PropValue>,
  ) -> Self {
    self.ops.push(BatchOp::Link {
      src,
      etype,
      dst,
      props,
    });
    self
  }

  /// Add an unlink operation
  pub fn unlink(mut self, src: NodeId, etype: ETypeId, dst: NodeId) -> Self {
    self.ops.push(BatchOp::Unlink { src, etype, dst });
    self
  }

  /// Get the collected operations
  pub fn build(self) -> Vec<BatchOp> {
    self.ops
  }

  /// Get the number of operations
  pub fn len(&self) -> usize {
    self.ops.len()
  }

  /// Check if empty
  pub fn is_empty(&self) -> bool {
    self.ops.is_empty()
  }
}

// ============================================================================
// Tests
// ============================================================================

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

  #[test]
  fn test_node_ref() {
    let node = NodeRef::new(1, "alice".to_string());
    assert_eq!(node.id(), 1);
    assert_eq!(node.key(), "alice");
    assert!(node.props().is_empty());
  }

  #[test]
  fn test_node_ref_with_props() {
    let mut props = HashMap::new();
    props.insert("name".to_string(), PropValue::String("Alice".to_string()));
    props.insert("age".to_string(), PropValue::I64(30));

    let node = NodeRef::with_props(1, "alice".to_string(), props);

    assert_eq!(
      node.prop("name"),
      Some(&PropValue::String("Alice".to_string()))
    );
    assert_eq!(node.prop("age"), Some(&PropValue::I64(30)));
    assert_eq!(node.prop("unknown"), None);
  }

  #[test]
  fn test_insert_data() {
    let data = InsertData::new()
      .with_key("alice")
      .with_prop(1, PropValue::String("Alice".to_string()))
      .with_prop(2, PropValue::I64(30));

    assert_eq!(data.key, Some("alice".to_string()));
    assert_eq!(data.props.len(), 2);
  }

  #[test]
  fn test_insert_builder() {
    let mut executed = false;
    let mut captured_data: Option<InsertData> = None;

    let mut executor = |data: InsertData| {
      executed = true;
      captured_data = Some(data);
      1u64 // Return node ID
    };

    let data = InsertData::new().with_key("test");
    let result = InsertBuilder::new("User", &mut executor).values(data);

    assert!(executed);
    assert_eq!(result, 1);
    assert_eq!(
      captured_data.expect("expected value").key,
      Some("test".to_string())
    );
  }

  #[test]
  fn test_update_builder() {
    let mut captured: Option<(NodeId, HashMap<PropKeyId, Option<PropValue>>)> = None;

    let mut executor = |node_id: NodeId, updates: HashMap<PropKeyId, Option<PropValue>>| {
      captured = Some((node_id, updates));
    };

    UpdateBuilder::new(&mut executor)
      .where_id(42)
      .set(1, PropValue::String("Updated".to_string()))
      .unset(2)
      .execute()
      .expect("expected value");

    let (node_id, updates) = captured.expect("expected value");
    assert_eq!(node_id, 42);
    assert_eq!(updates.len(), 2);
    assert!(updates.get(&1).expect("expected value").is_some());
    assert!(updates.get(&2).expect("expected value").is_none());
  }

  #[test]
  fn test_delete_builder() {
    let mut deleted_id: Option<NodeId> = None;

    let mut executor = |node_id: NodeId| {
      deleted_id = Some(node_id);
      true
    };

    let result = DeleteBuilder::new(&mut executor)
      .where_id(42)
      .execute()
      .expect("expected value");

    assert!(result);
    assert_eq!(deleted_id, Some(42));
  }

  #[test]
  fn test_link_builder() {
    let mut captured: Option<(NodeId, ETypeId, NodeId, HashMap<PropKeyId, PropValue>)> = None;

    let mut executor = |src, etype, dst, props| {
      captured = Some((src, etype, dst, props));
    };

    LinkBuilder::new(1, 10, &mut executor)
      .to(2)
      .with_prop(100, PropValue::F64(1.5))
      .execute()
      .expect("expected value");

    let (src, etype, dst, props) = captured.expect("expected value");
    assert_eq!(src, 1);
    assert_eq!(etype, 10);
    assert_eq!(dst, 2);
    assert_eq!(props.get(&100), Some(&PropValue::F64(1.5)));
  }

  #[test]
  fn test_unlink_builder() {
    let mut captured: Option<(NodeId, ETypeId, NodeId)> = None;

    let mut executor = |src, etype, dst| {
      captured = Some((src, etype, dst));
      true
    };

    let result = UnlinkBuilder::new(1, 10, &mut executor)
      .from_node(2)
      .execute()
      .expect("expected value");

    assert!(result);
    let (src, etype, dst) = captured.expect("expected value");
    assert_eq!(src, 1);
    assert_eq!(etype, 10);
    assert_eq!(dst, 2);
  }

  #[test]
  fn test_batch_builder() {
    let batch = BatchBuilder::new()
      .insert(InsertData::new().with_key("alice"))
      .insert(InsertData::new().with_key("bob"))
      .link(1, 10, 2)
      .update(1, HashMap::new())
      .delete(3)
      .unlink(1, 10, 2)
      .build();

    assert_eq!(batch.len(), 6);

    assert!(matches!(batch[0], BatchOp::Insert(_)));
    assert!(matches!(batch[1], BatchOp::Insert(_)));
    assert!(matches!(batch[2], BatchOp::Link { .. }));
    assert!(matches!(batch[3], BatchOp::Update { .. }));
    assert!(matches!(batch[4], BatchOp::Delete { .. }));
    assert!(matches!(batch[5], BatchOp::Unlink { .. }));
  }

  #[test]
  fn test_batch_builder_empty() {
    let batch = BatchBuilder::new();
    assert!(batch.is_empty());
    assert_eq!(batch.len(), 0);
  }
}