reddb-io-server 1.1.2

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
//! Fluent Builders for Entity Creation
//!
//! NodeBuilder, EdgeBuilder, VectorBuilder, RowBuilder, DocumentBuilder for fluent entity creation.

use std::collections::HashMap;
use std::sync::Arc;

use super::super::{
    CrossRef, EdgeData, EntityData, EntityId, EntityKind, GraphEdgeKind, GraphNodeKind, Metadata,
    MetadataValue, NodeData, RefType, RowData, UnifiedEntity, UnifiedStore, VectorData,
};
use super::error::DevXError;
use super::refs::{NodeRef, TableRef, VectorRef};
use super::{run_preprocessors, SharedPreprocessors};
use crate::json::{to_vec as json_to_vec, Value as JsonValue};
use crate::storage::schema::Value;

// ============================================================================
// Node Builder
// ============================================================================

/// Fluent builder for graph nodes
pub struct NodeBuilder {
    store: Arc<UnifiedStore>,
    preprocessors: SharedPreprocessors,
    collection: String,
    label: String,
    node_type: String,
    properties: HashMap<String, Value>,
    metadata: HashMap<String, MetadataValue>,
    embeddings: Vec<(String, Vec<f32>, String)>, // (name, vector, model)
    links: Vec<(EntityId, String, f32)>,         // (target, label, weight)
    cross_links: Vec<(EntityId, String, RefType)>, // (target, collection, ref_type)
}

impl NodeBuilder {
    pub(crate) fn new(
        store: Arc<UnifiedStore>,
        preprocessors: SharedPreprocessors,
        collection: impl Into<String>,
        label: impl Into<String>,
    ) -> Self {
        let label_str = label.into();
        Self {
            store,
            preprocessors,
            collection: collection.into(),
            label: label_str.clone(),
            node_type: label_str,
            properties: HashMap::new(),
            metadata: HashMap::new(),
            embeddings: Vec::new(),
            links: Vec::new(),
            cross_links: Vec::new(),
        }
    }

    /// Set node type (defaults to label)
    pub fn node_type(mut self, node_type: impl Into<String>) -> Self {
        self.node_type = node_type.into();
        self
    }

    /// Add a property
    pub fn property(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        self.properties.insert(key.into(), value.into());
        self
    }

    /// Add multiple properties at once
    pub fn properties(
        mut self,
        props: impl IntoIterator<Item = (impl Into<String>, impl Into<Value>)>,
    ) -> Self {
        for (k, v) in props {
            self.properties.insert(k.into(), v.into());
        }
        self
    }

    /// Add metadata
    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<MetadataValue>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Add metadata linking to a table row
    pub fn link_to_table(mut self, key: impl Into<String>, table_ref: TableRef) -> Self {
        self.metadata.insert(key.into(), table_ref.to_metadata());
        self.cross_links.push((
            EntityId::new(table_ref.row_id),
            table_ref.table.clone(),
            RefType::NodeToRow,
        ));
        self
    }

    /// Add metadata linking to another node
    pub fn link_to_node(mut self, key: impl Into<String>, node_ref: NodeRef) -> Self {
        self.metadata.insert(key.into(), node_ref.to_metadata());
        self
    }

    /// Add an embedding vector
    pub fn embedding(mut self, name: impl Into<String>, vector: Vec<f32>) -> Self {
        self.embeddings
            .push((name.into(), vector, "default".to_string()));
        self
    }

    /// Add an embedding with model name
    pub fn embedding_with_model(
        mut self,
        name: impl Into<String>,
        vector: Vec<f32>,
        model: impl Into<String>,
    ) -> Self {
        self.embeddings.push((name.into(), vector, model.into()));
        self
    }

    /// Link to another node (creates edge)
    pub fn link_to(mut self, target: EntityId, edge_label: impl Into<String>) -> Self {
        self.links.push((target, edge_label.into(), 1.0));
        self
    }

    /// Link to another node with weight
    pub fn link_to_weighted(
        mut self,
        target: EntityId,
        edge_label: impl Into<String>,
        weight: f32,
    ) -> Self {
        self.links.push((target, edge_label.into(), weight));
        self
    }

    /// Save the node and return its ID
    pub fn save(self) -> Result<EntityId, DevXError> {
        // Create the node entity
        let kind = EntityKind::GraphNode(Box::new(GraphNodeKind {
            label: self.label,
            node_type: self.node_type,
        }));

        let data = EntityData::Node(NodeData::with_properties(self.properties));

        let id = self.store.next_entity_id();

        let mut entity = UnifiedEntity::new(id, kind, data);

        // Add embeddings
        for (name, vector, model) in self.embeddings {
            entity.add_embedding(super::super::EmbeddingSlot::new(name, vector, model));
        }
        for (target, target_collection, ref_type) in self.cross_links {
            entity.add_cross_ref(CrossRef::new(id, target, target_collection, ref_type));
        }
        run_preprocessors(&self.preprocessors, &mut entity)?;

        // Insert the entity
        let id = self
            .store
            .insert_auto(&self.collection, entity)
            .map_err(|e| DevXError::Storage(format!("{:?}", e)))?;

        // Store metadata
        if !self.metadata.is_empty() {
            let _ = self.store.set_metadata(
                &self.collection,
                id,
                Metadata::with_fields(self.metadata.clone()),
            );
        }

        // Create edges for links
        for (target, edge_label, weight) in self.links {
            let edge_kind = EntityKind::GraphEdge(Box::new(GraphEdgeKind {
                label: edge_label,
                from_node: id.0.to_string(),
                to_node: target.0.to_string(),
                weight: (weight * 1000.0) as u32,
            }));

            let edge_data = EntityData::Edge(EdgeData::new(weight));
            let edge_id = self.store.next_entity_id();
            let mut edge_entity = UnifiedEntity::new(edge_id, edge_kind, edge_data);

            // Add cross-refs for fast traversal
            edge_entity.add_cross_ref(CrossRef::new(
                edge_id,
                target,
                self.collection.clone(),
                RefType::RelatedTo,
            ));

            run_preprocessors(&self.preprocessors, &mut edge_entity)?;
            let _ = self.store.insert_auto(&self.collection, edge_entity);

            // Add cross-ref from source node to edge
            let _ = self.store.add_cross_ref(
                &self.collection,
                id,
                &self.collection,
                edge_id,
                RefType::RelatedTo,
                1.0,
            );
        }

        Ok(id)
    }
}

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

/// Fluent builder for graph edges
pub struct EdgeBuilder {
    store: Arc<UnifiedStore>,
    preprocessors: SharedPreprocessors,
    collection: String,
    label: String,
    from_node: Option<EntityId>,
    to_node: Option<EntityId>,
    weight: f32,
    properties: HashMap<String, Value>,
    metadata: HashMap<String, MetadataValue>,
}

impl EdgeBuilder {
    pub(crate) fn new(
        store: Arc<UnifiedStore>,
        preprocessors: SharedPreprocessors,
        collection: impl Into<String>,
        label: impl Into<String>,
    ) -> Self {
        Self {
            store,
            preprocessors,
            collection: collection.into(),
            label: label.into(),
            from_node: None,
            to_node: None,
            weight: 1.0,
            properties: HashMap::new(),
            metadata: HashMap::new(),
        }
    }

    /// Set source node
    pub fn from(mut self, node_id: EntityId) -> Self {
        self.from_node = Some(node_id);
        self
    }

    /// Set target node
    pub fn to(mut self, node_id: EntityId) -> Self {
        self.to_node = Some(node_id);
        self
    }

    /// Set edge weight
    pub fn weight(mut self, weight: f32) -> Self {
        self.weight = weight;
        self
    }

    /// Add a property
    pub fn property(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
        self.properties.insert(key.into(), value.into());
        self
    }

    /// Add metadata
    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<MetadataValue>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Link metadata to a table row
    pub fn link_to_table(mut self, key: impl Into<String>, table_ref: TableRef) -> Self {
        self.metadata.insert(key.into(), table_ref.to_metadata());
        self
    }

    /// Save the edge
    pub fn save(self) -> Result<EntityId, DevXError> {
        let from = self
            .from_node
            .ok_or_else(|| DevXError::Validation("Edge requires 'from' node".into()))?;
        let to = self
            .to_node
            .ok_or_else(|| DevXError::Validation("Edge requires 'to' node".into()))?;

        let kind = EntityKind::GraphEdge(Box::new(GraphEdgeKind {
            label: self.label,
            from_node: from.0.to_string(),
            to_node: to.0.to_string(),
            weight: (self.weight * 1000.0) as u32,
        }));

        let mut edge_data = EdgeData::new(self.weight);
        edge_data.properties = self.properties;

        let id = self.store.next_entity_id();

        let mut entity = UnifiedEntity::new(id, kind, EntityData::Edge(edge_data));

        // Add cross-refs for bidirectional traversal
        entity.add_cross_ref(CrossRef::new(
            id,
            from,
            self.collection.clone(),
            RefType::DerivesFrom,
        ));
        entity.add_cross_ref(CrossRef::new(
            id,
            to,
            self.collection.clone(),
            RefType::RelatedTo,
        ));
        run_preprocessors(&self.preprocessors, &mut entity)?;

        let id = self
            .store
            .insert_auto(&self.collection, entity)
            .map_err(|e| DevXError::Storage(format!("{:?}", e)))?;

        // Store metadata
        if !self.metadata.is_empty() {
            let _ = self.store.set_metadata(
                &self.collection,
                id,
                Metadata::with_fields(self.metadata.clone()),
            );
        }

        // Update source and target nodes with cross-refs
        let _ = self.store.add_cross_ref(
            &self.collection,
            from,
            &self.collection,
            id,
            RefType::RelatedTo,
            1.0,
        );
        let _ = self.store.add_cross_ref(
            &self.collection,
            to,
            &self.collection,
            id,
            RefType::RelatedTo,
            1.0,
        );

        Ok(id)
    }
}

// ============================================================================
// Vector Builder
// ============================================================================

/// Fluent builder for vectors
pub struct VectorBuilder {
    store: Arc<UnifiedStore>,
    preprocessors: SharedPreprocessors,
    collection: String,
    dense: Option<Vec<f32>>,
    sparse: Option<Vec<(u32, f32)>>,
    content: Option<String>,
    metadata: HashMap<String, MetadataValue>,
    links: Vec<(EntityId, String, RefType)>,
}

impl VectorBuilder {
    pub(crate) fn new(
        store: Arc<UnifiedStore>,
        preprocessors: SharedPreprocessors,
        collection: impl Into<String>,
    ) -> Self {
        Self {
            store,
            preprocessors,
            collection: collection.into(),
            dense: None,
            sparse: None,
            content: None,
            metadata: HashMap::new(),
            links: Vec::new(),
        }
    }

    /// Set dense vector
    pub fn dense(mut self, vector: Vec<f32>) -> Self {
        self.dense = Some(vector);
        self
    }

    /// Set sparse vector
    pub fn sparse(mut self, indices_values: Vec<(u32, f32)>) -> Self {
        self.sparse = Some(indices_values);
        self
    }

    /// Set original content
    pub fn content(mut self, content: impl Into<String>) -> Self {
        self.content = Some(content.into());
        self
    }

    /// Add metadata
    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<MetadataValue>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Link to a table row
    pub fn link_to_table(mut self, table_ref: TableRef) -> Self {
        self.metadata
            .insert("_source_table".to_string(), table_ref.to_metadata());
        self.links.push((
            EntityId::new(table_ref.row_id),
            table_ref.table,
            RefType::VectorToRow,
        ));
        self
    }

    /// Link to a node
    pub fn link_to_node(mut self, node_ref: NodeRef) -> Self {
        self.links
            .push((node_ref.node_id, node_ref.collection, RefType::VectorToNode));
        self
    }

    /// Save the vector
    pub fn save(self) -> Result<EntityId, DevXError> {
        let dense = self
            .dense
            .ok_or_else(|| DevXError::Validation("Vector requires dense data".into()))?;

        // Capture dimension before moving dense
        let dense_len = dense.len();

        let kind = EntityKind::Vector {
            collection: self.collection.clone(),
        };

        let mut vec_data = VectorData::new(dense);
        vec_data.content = self.content;

        if let Some(sparse_data) = self.sparse {
            // Unzip indices and values from tuples
            let (indices, values): (Vec<u32>, Vec<f32>) = sparse_data.into_iter().unzip();
            // Dimension is dense length or max sparse index + 1
            let dimension = dense_len.max(
                indices
                    .iter()
                    .copied()
                    .max()
                    .map(|m| m as usize + 1)
                    .unwrap_or(0),
            );
            vec_data.sparse = Some(super::super::SparseVector::new(indices, values, dimension));
        }

        let id = self.store.next_entity_id();
        let mut entity = UnifiedEntity::new(id, kind, EntityData::Vector(vec_data));

        // Add cross-refs
        for (target, target_collection, ref_type) in self.links {
            entity.add_cross_ref(CrossRef::new(id, target, target_collection, ref_type));
        }
        run_preprocessors(&self.preprocessors, &mut entity)?;

        let id = self
            .store
            .insert_auto(&self.collection, entity)
            .map_err(|e| DevXError::Storage(format!("{:?}", e)))?;

        // Store metadata
        if !self.metadata.is_empty() {
            let _ =
                self.store
                    .set_metadata(&self.collection, id, Metadata::with_fields(self.metadata));
        }

        Ok(id)
    }
}

// ============================================================================
// Row Builder
// ============================================================================

/// Fluent builder for table rows
pub struct RowBuilder {
    store: Arc<UnifiedStore>,
    preprocessors: SharedPreprocessors,
    table: String,
    columns: Vec<Value>,
    named: HashMap<String, Value>,
    metadata: HashMap<String, MetadataValue>,
    links: Vec<(EntityId, String, RefType)>,
}

impl RowBuilder {
    pub(crate) fn new(
        store: Arc<UnifiedStore>,
        preprocessors: SharedPreprocessors,
        table: impl Into<String>,
        columns: Vec<(&str, Value)>,
    ) -> Self {
        let mut named = HashMap::new();
        let mut col_values = Vec::new();

        for (name, value) in columns {
            named.insert(name.to_string(), value.clone());
            col_values.push(value);
        }

        Self {
            store,
            preprocessors,
            table: table.into(),
            columns: col_values,
            named,
            metadata: HashMap::new(),
            links: Vec::new(),
        }
    }

    /// Add metadata
    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<MetadataValue>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Link to a node
    pub fn link_to_node(mut self, node_ref: NodeRef) -> Self {
        self.links
            .push((node_ref.node_id, node_ref.collection, RefType::RowToNode));
        self
    }

    /// Link to a vector
    pub fn link_to_vector(mut self, vector_ref: VectorRef) -> Self {
        self.links.push((
            vector_ref.vector_id,
            vector_ref.collection,
            RefType::RowToVector,
        ));
        self
    }

    /// Save the row
    pub fn save(self) -> Result<EntityId, DevXError> {
        let id = self.store.next_entity_id();

        // Per-table sequential row_id (1, 2, 3... per collection)
        let row_id = self
            .store
            .get_collection(&self.table)
            .map(|m| m.next_row_id())
            .unwrap_or(id.0);

        let kind = EntityKind::TableRow {
            table: Arc::from(self.table.as_str()),
            row_id,
        };

        let mut row_data = RowData::new(self.columns);
        row_data.named = Some(self.named);

        let mut entity = UnifiedEntity::new(id, kind, EntityData::Row(row_data));

        // Add cross-refs
        for (target, target_collection, ref_type) in self.links {
            entity.add_cross_ref(CrossRef::new(id, target, target_collection, ref_type));
        }
        run_preprocessors(&self.preprocessors, &mut entity)?;

        let id = self
            .store
            .insert_auto(&self.table, entity)
            .map_err(|e| DevXError::Storage(format!("{:?}", e)))?;

        // Store metadata
        if !self.metadata.is_empty() {
            let _ = self
                .store
                .set_metadata(&self.table, id, Metadata::with_fields(self.metadata));
        }

        Ok(id)
    }
}

// ============================================================================
// KV Builder
// ============================================================================

/// Fluent builder for key-value pairs
///
/// Stores KV pairs as table rows with named fields `key` (Text) and `value`.
pub struct KvBuilder {
    store: Arc<UnifiedStore>,
    preprocessors: SharedPreprocessors,
    collection: String,
    key: String,
    value: Value,
    metadata: HashMap<String, MetadataValue>,
}

impl KvBuilder {
    pub(crate) fn new(
        store: Arc<UnifiedStore>,
        preprocessors: SharedPreprocessors,
        collection: impl Into<String>,
        key: impl Into<String>,
        value: Value,
    ) -> Self {
        Self {
            store,
            preprocessors,
            collection: collection.into(),
            key: key.into(),
            value,
            metadata: HashMap::new(),
        }
    }

    /// Add metadata
    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<MetadataValue>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Save the key-value pair as a table row with named fields `key` and `value`
    pub fn save(self) -> Result<EntityId, DevXError> {
        let Self {
            store,
            preprocessors,
            collection,
            key,
            value,
            metadata,
        } = self;

        let columns = vec![("key", Value::text(key)), ("value", value)];
        let mut builder = RowBuilder::new(store, preprocessors, &collection, columns);
        for (k, v) in metadata {
            builder = builder.metadata(k, v);
        }
        builder.save()
    }
}

// ============================================================================
// Document Builder
// ============================================================================

/// Fluent builder for documents stored as enriched table rows.
///
/// Documents are stored as `TableRow` entities with:
/// - A `body` named field containing the full JSON serialized as `Value::Json`
/// - Flattened top-level keys from the body as additional named fields for filtering
///
/// # Example
/// ```ignore
/// let doc = db.doc("articles")
///     .field("title", "First Post")
///     .field("views", 42)
///     .metadata("source", "web")
///     .save()?;
/// ```
pub struct DocumentBuilder {
    store: Arc<UnifiedStore>,
    preprocessors: SharedPreprocessors,
    collection: String,
    body: HashMap<String, JsonValue>,
    metadata: HashMap<String, MetadataValue>,
    links: Vec<(EntityId, String, RefType)>,
}

impl DocumentBuilder {
    pub(crate) fn new(
        store: Arc<UnifiedStore>,
        preprocessors: SharedPreprocessors,
        collection: impl Into<String>,
    ) -> Self {
        Self {
            store,
            preprocessors,
            collection: collection.into(),
            body: HashMap::new(),
            metadata: HashMap::new(),
            links: Vec::new(),
        }
    }

    /// Set a document field
    pub fn field(mut self, key: impl Into<String>, value: impl Into<JsonValue>) -> Self {
        self.body.insert(key.into(), value.into());
        self
    }

    /// Add metadata
    pub fn metadata(mut self, key: impl Into<String>, value: impl Into<MetadataValue>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Link to a graph node
    pub fn link_to_node(mut self, node_ref: NodeRef) -> Self {
        self.links
            .push((node_ref.node_id, node_ref.collection, RefType::RowToNode));
        self
    }

    /// Link to a vector
    pub fn link_to_vector(mut self, vector_ref: VectorRef) -> Self {
        self.links.push((
            vector_ref.vector_id,
            vector_ref.collection,
            RefType::RowToVector,
        ));
        self
    }

    /// Save the document and return its ID
    pub fn save(self) -> Result<EntityId, DevXError> {
        let id = self.store.next_entity_id();

        let kind = EntityKind::TableRow {
            table: Arc::from(self.collection.as_str()),
            row_id: id.0,
        };

        // Build the full JSON body object
        let body_object = JsonValue::Object(
            self.body
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect(),
        );
        let body_bytes = json_to_vec(&body_object)
            .map_err(|e| DevXError::Storage(format!("failed to serialize document body: {e}")))?;

        // Build named fields: "body" (full JSON) + flattened top-level keys
        let mut named = HashMap::new();
        named.insert("body".to_string(), Value::Json(body_bytes));

        for (key, value) in &self.body {
            let storage_value = json_value_to_storage_value(value);
            named.insert(key.clone(), storage_value);
        }

        let mut row_data = RowData::new(Vec::new());
        row_data.named = Some(named);

        let mut entity = UnifiedEntity::new(id, kind, EntityData::Row(row_data));

        // Add cross-refs
        for (target, target_collection, ref_type) in self.links {
            entity.add_cross_ref(CrossRef::new(id, target, target_collection, ref_type));
        }
        run_preprocessors(&self.preprocessors, &mut entity)?;

        let id = self
            .store
            .insert_auto(&self.collection, entity)
            .map_err(|e| DevXError::Storage(format!("{:?}", e)))?;

        // Store metadata
        if !self.metadata.is_empty() {
            let _ =
                self.store
                    .set_metadata(&self.collection, id, Metadata::with_fields(self.metadata));
        }

        Ok(id)
    }
}

/// Convert a JSON value to a storage value for flattened document fields.
fn json_value_to_storage_value(value: &JsonValue) -> Value {
    match value {
        JsonValue::Null => Value::Null,
        JsonValue::Bool(b) => Value::Boolean(*b),
        JsonValue::Number(n) => {
            if n.fract().abs() < f64::EPSILON {
                Value::Integer(*n as i64)
            } else {
                Value::Float(*n)
            }
        }
        JsonValue::String(s) => Value::text(s.clone()),
        JsonValue::Array(_) | JsonValue::Object(_) => match json_to_vec(value) {
            Ok(bytes) => Value::Json(bytes),
            Err(_) => Value::Null,
        },
    }
}