Skip to main content

reddb_server/application/
entity.rs

1use std::collections::HashMap;
2
3use crate::application::ports::RuntimeEntityPort;
4use crate::json::{parse_json, to_vec as json_to_vec, Map, Value as JsonValue};
5use crate::storage::unified::devx::refs::{NodeRef, TableRef, VectorRef};
6use crate::storage::unified::{Metadata, MetadataValue, RefTarget, SparseVector, VectorData};
7use crate::storage::{EntityId, UnifiedEntity};
8use crate::{RedDBError, RedDBResult};
9use reddb_types::Value;
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::sync::Arc;
12
13pub(crate) struct AutocommitUpdate {
14    manager: Arc<crate::storage::transaction::snapshot::SnapshotManager>,
15    pub(crate) xid: u64,
16    finished: AtomicBool,
17}
18
19impl AutocommitUpdate {
20    /// An autocommit update of rows of `collection` and of nothing else.
21    pub(crate) fn new(
22        manager: Arc<crate::storage::transaction::snapshot::SnapshotManager>,
23        collection: &str,
24    ) -> Arc<Self> {
25        let xid = manager.begin_cache_coherent_update_in(collection);
26        Arc::new(Self {
27            manager,
28            xid,
29            finished: AtomicBool::new(false),
30        })
31    }
32
33    pub(crate) fn commit(&self) {
34        if !self.finished.swap(true, Ordering::AcqRel) {
35            self.manager.commit(self.xid);
36        }
37    }
38}
39
40impl std::fmt::Debug for AutocommitUpdate {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("AutocommitUpdate")
43            .field("xid", &self.xid)
44            .finish()
45    }
46}
47
48impl Drop for AutocommitUpdate {
49    fn drop(&mut self) {
50        if !self.finished.load(Ordering::Acquire) {
51            self.manager.rollback(self.xid);
52        }
53    }
54}
55
56#[derive(Debug, Clone)]
57pub struct CreateEntityOutput {
58    pub id: EntityId,
59    pub entity: Option<UnifiedEntity>,
60}
61
62#[derive(Debug, Clone)]
63pub struct AppliedEntityMutation {
64    pub(crate) autocommit_update: Option<Arc<AutocommitUpdate>>,
65    pub id: EntityId,
66    pub collection: String,
67    pub entity: UnifiedEntity,
68    pub metadata: Option<crate::storage::unified::Metadata>,
69    pub modified_columns: Vec<String>,
70    pub persist_metadata: bool,
71    pub context_index_dirty: bool,
72    /// Prior physical version retained for MVCC history. Present when an
73    /// UPDATE creates a new physical entity for the same logical row.
74    pub replaced_entity: Option<UnifiedEntity>,
75    /// xmax carried by `replaced_entity` before this mutation stamped it.
76    pub replaced_entity_previous_xmax: u64,
77    /// Snapshot of the row's named fields BEFORE the mutation was
78    /// applied. Carried so the post-write secondary-index hook can
79    /// `delete(old) + insert(new)` for changed indexed columns.
80    /// Empty when the entity isn't a row or the row carried neither a
81    /// `named` map nor a `schema` Arc.
82    pub pre_mutation_fields: Vec<(String, Value)>,
83}
84
85/// Damage-vector for a row update: the minimal diff between the
86/// pre-mutation and post-mutation field state. Downstream consumers
87/// (secondary-index maintainer, CDC emitter, eventually the pager's
88/// in-place update path) work off this struct so they only touch
89/// columns that actually changed.
90///
91/// Future work (Fase 5): the pager can decide whether `changed` fits
92/// in the existing cell's slotted footprint and patch bytes in place
93/// instead of rewriting the whole row.
94#[derive(Debug, Clone, Default, PartialEq)]
95pub struct RowDamageVector {
96    /// Columns present in both `old` and `new` whose value differs.
97    /// `(column, old_value, new_value)`.
98    pub changed: Vec<(String, Value, Value)>,
99    /// Columns present in `new` but not in `old`.
100    pub added: Vec<(String, Value)>,
101    /// Columns present in `old` but not in `new`.
102    pub removed: Vec<(String, Value)>,
103}
104
105impl RowDamageVector {
106    /// True when no columns changed, were added, or were removed.
107    /// Callers can short-circuit index/CDC/in-place work when this
108    /// holds.
109    pub fn is_empty(&self) -> bool {
110        self.changed.is_empty() && self.added.is_empty() && self.removed.is_empty()
111    }
112
113    /// Names of every column the update touched. Equivalent to the
114    /// current `modified_columns` list carried on `AppliedEntityMutation`
115    /// but computed from the ground truth of old/new rather than
116    /// from what the SQL executor thinks it wrote.
117    pub fn touched_columns(&self) -> Vec<&str> {
118        let mut out: Vec<&str> =
119            Vec::with_capacity(self.changed.len() + self.added.len() + self.removed.len());
120        out.extend(self.changed.iter().map(|(c, _, _)| c.as_str()));
121        out.extend(self.added.iter().map(|(c, _)| c.as_str()));
122        out.extend(self.removed.iter().map(|(c, _)| c.as_str()));
123        out
124    }
125}
126
127/// Compute the damage-vector between an old and new row snapshot.
128/// Both inputs are field lists (as carried by `CreateRowInput` and
129/// `AppliedEntityMutation.pre_mutation_fields`); the order of fields
130/// is not significant. Columns present in both sides with identical
131/// values don't appear in any bucket.
132pub fn row_damage_vector(
133    old_fields: &[(String, Value)],
134    new_fields: &[(String, Value)],
135) -> RowDamageVector {
136    // HashMap<&str, &Value> keyed by column name for O(1) membership
137    // checks. Both inputs are expected to be small (tens of columns),
138    // so the allocation overhead is negligible vs the O(N*M) pairwise
139    // comparison we'd otherwise need.
140    let old_map: HashMap<&str, &Value> = old_fields.iter().map(|(k, v)| (k.as_str(), v)).collect();
141    let new_map: HashMap<&str, &Value> = new_fields.iter().map(|(k, v)| (k.as_str(), v)).collect();
142
143    let mut changed = Vec::new();
144    let mut added = Vec::new();
145    let mut removed = Vec::new();
146
147    for (name, new_value) in &new_map {
148        match old_map.get(name) {
149            Some(old_value) if old_value == new_value => {}
150            Some(old_value) => changed.push((
151                (*name).to_string(),
152                (*old_value).clone(),
153                (*new_value).clone(),
154            )),
155            None => added.push(((*name).to_string(), (*new_value).clone())),
156        }
157    }
158    for (name, old_value) in &old_map {
159        if !new_map.contains_key(name) {
160            removed.push(((*name).to_string(), (*old_value).clone()));
161        }
162    }
163
164    RowDamageVector {
165        changed,
166        added,
167        removed,
168    }
169}
170
171pub use reddb_engine::catalog::enforcement::{RowUpdateColumnRule, RowUpdateContractPlan};
172
173#[derive(Debug, Clone)]
174pub struct CreateRowInput {
175    pub collection: String,
176    pub fields: Vec<(String, Value)>,
177    pub metadata: Vec<(String, MetadataValue)>,
178    pub node_links: Vec<NodeRef>,
179    pub vector_links: Vec<VectorRef>,
180}
181
182#[derive(Debug, Clone)]
183pub struct CreateRowsBatchInput {
184    pub collection: String,
185    pub rows: Vec<CreateRowInput>,
186    /// When true, no event subscriptions fire for this batch (SUPPRESS EVENTS).
187    pub suppress_events: bool,
188}
189
190#[derive(Debug, Clone)]
191pub struct CreateNodeEmbeddingInput {
192    pub name: String,
193    pub vector: Vec<f32>,
194    pub model: Option<String>,
195}
196
197#[derive(Debug, Clone)]
198pub struct CreateNodeTableLinkInput {
199    pub key: String,
200    pub table: TableRef,
201}
202
203#[derive(Debug, Clone)]
204pub struct CreateNodeGraphLinkInput {
205    pub target: EntityId,
206    pub edge_label: String,
207    pub weight: f32,
208}
209
210#[derive(Debug, Clone)]
211pub struct CreateNodeInput {
212    pub collection: String,
213    pub label: String,
214    pub node_type: Option<String>,
215    pub properties: Vec<(String, Value)>,
216    pub metadata: Vec<(String, MetadataValue)>,
217    pub embeddings: Vec<CreateNodeEmbeddingInput>,
218    pub table_links: Vec<CreateNodeTableLinkInput>,
219    pub node_links: Vec<CreateNodeGraphLinkInput>,
220}
221
222#[derive(Debug, Clone)]
223pub struct CreateEdgeInput {
224    pub collection: String,
225    pub label: String,
226    pub from: EntityId,
227    pub to: EntityId,
228    pub weight: Option<f32>,
229    pub properties: Vec<(String, Value)>,
230    pub metadata: Vec<(String, MetadataValue)>,
231}
232
233#[derive(Debug, Clone)]
234pub struct CreateVectorInput {
235    pub collection: String,
236    pub dense: Vec<f32>,
237    pub content: Option<String>,
238    pub metadata: Vec<(String, MetadataValue)>,
239    pub link_row: Option<TableRef>,
240    pub link_node: Option<NodeRef>,
241}
242
243#[derive(Debug, Clone)]
244pub struct CreateDocumentInput {
245    pub collection: String,
246    pub body: JsonValue,
247    pub metadata: Vec<(String, MetadataValue)>,
248    pub node_links: Vec<NodeRef>,
249    pub vector_links: Vec<VectorRef>,
250}
251
252#[derive(Debug, Clone)]
253pub struct CreateKvInput {
254    pub collection: String,
255    pub key: String,
256    pub value: Value,
257    pub metadata: Vec<(String, MetadataValue)>,
258}
259
260#[derive(Debug, Clone)]
261pub struct CreateTimeSeriesPointInput {
262    pub collection: String,
263    pub metric: String,
264    pub value: f64,
265    pub timestamp_ns: Option<u64>,
266    pub tags: Vec<(String, String)>,
267    pub metadata: Vec<(String, MetadataValue)>,
268}
269
270#[derive(Debug, Clone)]
271pub struct DeleteEntityInput {
272    pub collection: String,
273    pub id: EntityId,
274}
275
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277pub enum PatchEntityOperationType {
278    Set,
279    Replace,
280    Unset,
281}
282
283#[derive(Debug, Clone)]
284pub struct PatchEntityOperation {
285    pub op: PatchEntityOperationType,
286    pub path: Vec<String>,
287    pub value: Option<JsonValue>,
288}
289
290#[derive(Debug, Clone)]
291pub struct PatchEntityInput {
292    pub collection: String,
293    pub id: EntityId,
294    pub payload: JsonValue,
295    pub operations: Vec<PatchEntityOperation>,
296}
297
298#[derive(Debug, Clone, Copy, PartialEq, Eq)]
299pub struct DeleteEntityOutput {
300    pub deleted: bool,
301    pub id: EntityId,
302}
303
304pub struct EntityUseCases<'a, P: ?Sized> {
305    runtime: &'a P,
306}
307
308impl<'a, P: RuntimeEntityPort + ?Sized> EntityUseCases<'a, P> {
309    pub fn new(runtime: &'a P) -> Self {
310        Self { runtime }
311    }
312
313    pub fn create_row(&self, input: CreateRowInput) -> RedDBResult<CreateEntityOutput> {
314        self.runtime.create_row(input)
315    }
316
317    pub fn create_rows_batch(
318        &self,
319        input: CreateRowsBatchInput,
320    ) -> RedDBResult<Vec<CreateEntityOutput>> {
321        self.runtime.create_rows_batch(input)
322    }
323
324    pub fn create_node(&self, input: CreateNodeInput) -> RedDBResult<CreateEntityOutput> {
325        self.runtime.create_node(input)
326    }
327
328    pub fn create_edge(&self, input: CreateEdgeInput) -> RedDBResult<CreateEntityOutput> {
329        self.runtime.create_edge(input)
330    }
331
332    pub fn create_vector(&self, input: CreateVectorInput) -> RedDBResult<CreateEntityOutput> {
333        self.runtime.create_vector(input)
334    }
335
336    pub fn create_document(&self, input: CreateDocumentInput) -> RedDBResult<CreateEntityOutput> {
337        self.runtime.create_document(input)
338    }
339
340    pub fn create_kv(&self, input: CreateKvInput) -> RedDBResult<CreateEntityOutput> {
341        self.runtime.create_kv(input)
342    }
343
344    pub fn create_timeseries_point(
345        &self,
346        input: CreateTimeSeriesPointInput,
347    ) -> RedDBResult<CreateEntityOutput> {
348        self.runtime.create_timeseries_point(input)
349    }
350
351    pub fn get_kv(&self, collection: &str, key: &str) -> RedDBResult<Option<(Value, EntityId)>> {
352        self.runtime.get_kv(collection, key)
353    }
354
355    pub fn delete_kv(&self, collection: &str, key: &str) -> RedDBResult<bool> {
356        self.runtime.delete_kv(collection, key)
357    }
358
359    pub fn patch(&self, input: PatchEntityInput) -> RedDBResult<CreateEntityOutput> {
360        self.runtime.patch_entity(input)
361    }
362
363    pub fn delete(&self, input: DeleteEntityInput) -> RedDBResult<DeleteEntityOutput> {
364        self.runtime.delete_entity(input)
365    }
366}
367
368pub(crate) fn json_to_storage_value(value: &JsonValue) -> RedDBResult<Value> {
369    match value {
370        JsonValue::Null => Ok(Value::Null),
371        JsonValue::Bool(value) => Ok(Value::Boolean(*value)),
372        JsonValue::Integer(value) => Ok(Value::Integer(*value)),
373        JsonValue::Number(value) => {
374            if value.fract().abs() < f64::EPSILON {
375                Ok(Value::Integer(*value as i64))
376            } else {
377                Ok(Value::Float(*value))
378            }
379        }
380        JsonValue::Decimal(value) => Ok(Value::DecimalText(value.clone())),
381        JsonValue::String(value) => Ok(Value::text(value.clone())),
382        JsonValue::Array(_) | JsonValue::Object(_) => json_to_vec(value)
383            .map(Value::Json)
384            .map_err(|err| RedDBError::Query(format!("failed to serialize JSON value: {err}"))),
385    }
386}
387
388pub(crate) fn json_to_metadata_value(value: &JsonValue) -> RedDBResult<MetadataValue> {
389    match value {
390        JsonValue::Null => Ok(MetadataValue::Null),
391        JsonValue::Bool(value) => Ok(MetadataValue::Bool(*value)),
392        JsonValue::Integer(value) => Ok(MetadataValue::Int(*value)),
393        JsonValue::Number(value) => {
394            if value.fract().abs() < f64::EPSILON {
395                Ok(MetadataValue::Int(*value as i64))
396            } else {
397                Ok(MetadataValue::Float(*value))
398            }
399        }
400        JsonValue::Decimal(value) => Ok(MetadataValue::String(value.clone())),
401        JsonValue::String(value) => Ok(MetadataValue::String(value.clone())),
402        JsonValue::Array(values) => {
403            let mut items = Vec::with_capacity(values.len());
404            for value in values {
405                items.push(json_to_metadata_value(value)?);
406            }
407            Ok(MetadataValue::Array(items))
408        }
409        JsonValue::Object(map) => {
410            let mut object = HashMap::with_capacity(map.len());
411            for (key, value) in map {
412                object.insert(key.clone(), json_to_metadata_value(value)?);
413            }
414            Ok(MetadataValue::Object(object))
415        }
416    }
417}
418
419pub(crate) fn apply_patch_operations_to_storage_map(
420    fields: &mut HashMap<String, Value>,
421    operations: &[PatchEntityOperation],
422) -> RedDBResult<()> {
423    if operations.is_empty() {
424        return Ok(());
425    }
426
427    let mut patch_target = JsonValue::Object(
428        fields
429            .iter()
430            .map(|(key, value)| (key.clone(), value.to_json()))
431            .collect(),
432    );
433    apply_patch_operations_to_json(&mut patch_target, operations)
434        .map_err(|error| RedDBError::Query(format!("patch fields failed: {error}")))?;
435
436    let JsonValue::Object(object) = patch_target else {
437        return Err(RedDBError::Query(
438            "patch operations require object roots".to_string(),
439        ));
440    };
441
442    let mut merged = HashMap::with_capacity(object.len());
443    for (key, value) in object {
444        merged.insert(key, json_to_storage_value(&value)?);
445    }
446    *fields = merged;
447    Ok(())
448}
449
450/// `pub` re-export of [`apply_patch_operations_to_json`] for the HTTP layer.
451/// The KV patch handler (issue #751) parses a JSON value, applies operations
452/// against the live JSON tree, and writes back — without reaching the
453/// entity-row patch core that this module otherwise owns.
454pub fn apply_patch_operations_to_json_public(
455    value: &mut JsonValue,
456    operations: &[PatchEntityOperation],
457) -> Result<(), String> {
458    apply_patch_operations_to_json(value, operations)
459}
460
461pub(crate) fn apply_patch_operations_to_json(
462    value: &mut JsonValue,
463    operations: &[PatchEntityOperation],
464) -> Result<(), String> {
465    for operation in operations {
466        if operation.path.is_empty() {
467            return Err("patch path cannot be empty".to_string());
468        }
469
470        match operation.op {
471            PatchEntityOperationType::Set | PatchEntityOperationType::Replace => {
472                let Some(patch_value) = &operation.value else {
473                    return Err("set/replace operations require a value".to_string());
474                };
475                apply_patch_json_set(value, &operation.path, patch_value.clone())?;
476            }
477            PatchEntityOperationType::Unset => {
478                apply_patch_json_unset(value, &operation.path)?;
479            }
480        }
481    }
482    Ok(())
483}
484
485pub(crate) fn apply_patch_operations_to_vector_fields(
486    vector: &mut VectorData,
487    operations: &[PatchEntityOperation],
488) -> RedDBResult<()> {
489    if operations.is_empty() {
490        return Ok(());
491    }
492
493    let mut vector_target = JsonValue::Object({
494        let mut object = Map::new();
495        object.insert(
496            "dense".to_string(),
497            JsonValue::Array(
498                vector
499                    .dense
500                    .iter()
501                    .map(|value| JsonValue::Number(*value as f64))
502                    .collect(),
503            ),
504        );
505        object.insert(
506            "sparse".to_string(),
507            vector.sparse.as_ref().map_or(JsonValue::Null, |sparse| {
508                let mut object = Map::new();
509                object.insert(
510                    "indices".to_string(),
511                    JsonValue::Array(
512                        sparse
513                            .indices
514                            .iter()
515                            .map(|value| JsonValue::Number(*value as f64))
516                            .collect(),
517                    ),
518                );
519                object.insert(
520                    "values".to_string(),
521                    JsonValue::Array(
522                        sparse
523                            .values
524                            .iter()
525                            .map(|value| JsonValue::Number(*value as f64))
526                            .collect(),
527                    ),
528                );
529                object.insert(
530                    "dimension".to_string(),
531                    JsonValue::Number(sparse.dimension as f64),
532                );
533                JsonValue::Object(object)
534            }),
535        );
536        object.insert(
537            "content".to_string(),
538            match vector.content.as_ref() {
539                Some(value) => JsonValue::String(value.clone()),
540                None => JsonValue::Null,
541            },
542        );
543        object
544    });
545
546    let touched_dense = operations
547        .iter()
548        .any(|operation| operation.path.first().is_some_and(|key| key == "dense"));
549    let touched_sparse = operations
550        .iter()
551        .any(|operation| operation.path.first().is_some_and(|key| key == "sparse"));
552    let touched_content = operations
553        .iter()
554        .any(|operation| operation.path.first().is_some_and(|key| key == "content"));
555
556    apply_patch_operations_to_json(&mut vector_target, operations)
557        .map_err(|error| RedDBError::Query(format!("patch fields failed: {error}")))?;
558
559    let JsonValue::Object(object) = vector_target else {
560        return Err(RedDBError::Query(
561            "patch operations require object roots".to_string(),
562        ));
563    };
564
565    if touched_dense {
566        let Some(value) = object.get("dense") else {
567            return Err(RedDBError::Query(
568                "field 'dense' cannot be unset".to_string(),
569            ));
570        };
571        vector.dense = parse_patch_f32_vector(value, "dense")?;
572    }
573
574    if touched_content {
575        vector.content = match object.get("content") {
576            None | Some(JsonValue::Null) => None,
577            Some(value) => Some(
578                value
579                    .as_str()
580                    .ok_or_else(|| {
581                        RedDBError::Query("field 'content' must be a string".to_string())
582                    })?
583                    .to_string(),
584            ),
585        };
586    }
587
588    if touched_sparse {
589        vector.sparse = match object.get("sparse") {
590            Some(value) => parse_sparse_vector_value(value)?,
591            None => None,
592        };
593    }
594
595    Ok(())
596}
597
598pub(crate) fn metadata_to_json(metadata: &Metadata) -> JsonValue {
599    JsonValue::Object(
600        metadata
601            .iter()
602            .map(|(key, value)| (key.clone(), metadata_value_to_json(value)))
603            .collect(),
604    )
605}
606
607pub(crate) fn metadata_from_json(payload: &JsonValue) -> RedDBResult<Metadata> {
608    let JsonValue::Object(object) = payload else {
609        return Err(RedDBError::Query(
610            "metadata patch requires an object".to_string(),
611        ));
612    };
613
614    let mut metadata = Metadata::new();
615    for (key, value) in object {
616        metadata.set(key.clone(), metadata_value_from_json(value)?);
617    }
618    Ok(metadata)
619}
620
621fn metadata_value_to_json(value: &MetadataValue) -> JsonValue {
622    match value {
623        MetadataValue::Null => JsonValue::Null,
624        MetadataValue::Bool(value) => JsonValue::Bool(*value),
625        MetadataValue::Int(value) => JsonValue::Number(*value as f64),
626        MetadataValue::Float(value) => JsonValue::Number(*value),
627        MetadataValue::String(value) => JsonValue::String(value.clone()),
628        MetadataValue::Bytes(value) => {
629            let mut object = Map::new();
630            object.insert(
631                "__redb_type".to_string(),
632                JsonValue::String("bytes".to_string()),
633            );
634            object.insert(
635                "value".to_string(),
636                JsonValue::Array(
637                    value
638                        .iter()
639                        .map(|value| JsonValue::Number(*value as f64))
640                        .collect(),
641                ),
642            );
643            JsonValue::Object(object)
644        }
645        MetadataValue::Array(values) => {
646            JsonValue::Array(values.iter().map(metadata_value_to_json).collect())
647        }
648        MetadataValue::Object(object) => JsonValue::Object(
649            object
650                .iter()
651                .map(|(key, value)| (key.clone(), metadata_value_to_json(value)))
652                .collect(),
653        ),
654        MetadataValue::Timestamp(value) => JsonValue::Number(*value as f64),
655        MetadataValue::Geo { lat, lon } => {
656            let mut object = Map::new();
657            object.insert(
658                "__redb_type".to_string(),
659                JsonValue::String("geo".to_string()),
660            );
661            object.insert("lat".to_string(), JsonValue::Number(*lat));
662            object.insert("lon".to_string(), JsonValue::Number(*lon));
663            JsonValue::Object(object)
664        }
665        MetadataValue::Reference(value) => {
666            let mut object = Map::new();
667            object.insert(
668                "__redb_type".to_string(),
669                JsonValue::String("reference".to_string()),
670            );
671            let (kind, collection, id) = match value {
672                RefTarget::TableRow { table, row_id } => ("table_row", table.as_str(), *row_id),
673                RefTarget::Node {
674                    collection,
675                    node_id,
676                } => ("node", collection.as_str(), node_id.raw()),
677                RefTarget::Edge {
678                    collection,
679                    edge_id,
680                } => ("edge", collection.as_str(), edge_id.raw()),
681                RefTarget::Vector {
682                    collection,
683                    vector_id,
684                } => ("vector", collection.as_str(), vector_id.raw()),
685                RefTarget::Entity {
686                    collection,
687                    entity_id,
688                } => ("entity", collection.as_str(), entity_id.raw()),
689            };
690            object.insert("kind".to_string(), JsonValue::String(kind.to_string()));
691            object.insert(
692                "collection".to_string(),
693                JsonValue::String(collection.to_string()),
694            );
695            object.insert("id".to_string(), JsonValue::Number(id as f64));
696            JsonValue::Object(object)
697        }
698        MetadataValue::References(values) => {
699            let mut object = Map::new();
700            object.insert(
701                "__redb_type".to_string(),
702                JsonValue::String("references".to_string()),
703            );
704            object.insert(
705                "values".to_string(),
706                JsonValue::Array(
707                    values
708                        .iter()
709                        .map(|r| metadata_value_to_json(&MetadataValue::Reference(r.clone())))
710                        .collect(),
711                ),
712            );
713            JsonValue::Object(object)
714        }
715    }
716}
717
718fn metadata_value_from_json(value: &JsonValue) -> RedDBResult<MetadataValue> {
719    match value {
720        JsonValue::Null => Ok(MetadataValue::Null),
721        JsonValue::Bool(value) => Ok(MetadataValue::Bool(*value)),
722        JsonValue::Integer(value) => Ok(MetadataValue::Int(*value)),
723        JsonValue::Number(value) => {
724            if value.fract().abs() < f64::EPSILON {
725                Ok(MetadataValue::Int(*value as i64))
726            } else {
727                Ok(MetadataValue::Float(*value))
728            }
729        }
730        JsonValue::Decimal(value) => Ok(MetadataValue::String(value.clone())),
731        JsonValue::String(value) => Ok(MetadataValue::String(value.clone())),
732        JsonValue::Array(values) => {
733            let mut out = Vec::with_capacity(values.len());
734            for value in values {
735                out.push(metadata_value_from_json(value)?);
736            }
737            Ok(MetadataValue::Array(out))
738        }
739        JsonValue::Object(object) => {
740            if let Some(marker) = object.get("__redb_type").and_then(JsonValue::as_str) {
741                match marker {
742                    "bytes" => {
743                        let values = object
744                            .get("value")
745                            .and_then(JsonValue::as_array)
746                            .ok_or_else(|| {
747                                RedDBError::Query(
748                                    "metadata marker 'bytes' requires array value".to_string(),
749                                )
750                            })?;
751                        let mut out = Vec::with_capacity(values.len());
752                        for value in values {
753                            let value = value.as_i64().ok_or_else(|| {
754                                RedDBError::Query(
755                                    "metadata bytes must contain integer values".to_string(),
756                                )
757                            })?;
758                            if !(0..=255).contains(&value) {
759                                return Err(RedDBError::Query(
760                                    "metadata bytes must contain values between 0 and 255"
761                                        .to_string(),
762                                ));
763                            }
764                            out.push(value as u8);
765                        }
766                        return Ok(MetadataValue::Bytes(out));
767                    }
768                    "geo" => {
769                        let lat =
770                            object
771                                .get("lat")
772                                .and_then(JsonValue::as_f64)
773                                .ok_or_else(|| {
774                                    RedDBError::Query(
775                                        "metadata marker 'geo' requires numeric 'lat'".to_string(),
776                                    )
777                                })?;
778                        let lon =
779                            object
780                                .get("lon")
781                                .and_then(JsonValue::as_f64)
782                                .ok_or_else(|| {
783                                    RedDBError::Query(
784                                        "metadata marker 'geo' requires numeric 'lon'".to_string(),
785                                    )
786                                })?;
787                        return Ok(MetadataValue::Geo { lat, lon });
788                    }
789                    "reference" => {
790                        return parse_metadata_reference(object).map(MetadataValue::Reference)
791                    }
792                    "references" => {
793                        let values = object
794                            .get("values")
795                            .and_then(JsonValue::as_array)
796                            .ok_or_else(|| {
797                                RedDBError::Query(
798                                    "metadata marker 'references' requires array 'values'"
799                                        .to_string(),
800                                )
801                            })?;
802                        let mut references = Vec::with_capacity(values.len());
803                        for value in values {
804                            references.push(parse_metadata_reference_value(value)?);
805                        }
806                        return Ok(MetadataValue::References(references));
807                    }
808                    _ => {}
809                }
810            }
811
812            let mut out = HashMap::with_capacity(object.len());
813            for (key, value) in object {
814                out.insert(key.clone(), metadata_value_from_json(value)?);
815            }
816            Ok(MetadataValue::Object(out))
817        }
818    }
819}
820
821fn parse_metadata_reference(object: &Map<String, JsonValue>) -> RedDBResult<RefTarget> {
822    let kind = object
823        .get("kind")
824        .and_then(JsonValue::as_str)
825        .ok_or_else(|| RedDBError::Query("metadata reference requires 'kind'".to_string()))?;
826    let collection = object
827        .get("collection")
828        .and_then(JsonValue::as_str)
829        .ok_or_else(|| RedDBError::Query("metadata reference requires 'collection'".to_string()))?;
830    let id = object
831        .get("id")
832        .ok_or_else(|| RedDBError::Query("metadata reference requires 'id'".to_string()))?;
833    let id = parse_patch_u64_value(id, "id")?;
834
835    let target = match kind {
836        "table_row" | "table" => RefTarget::table(collection.to_string(), id),
837        "node" => RefTarget::node(collection.to_string(), EntityId::new(id)),
838        "edge" => RefTarget::Edge {
839            collection: collection.to_string(),
840            edge_id: EntityId::new(id),
841        },
842        "vector" => RefTarget::vector(collection.to_string(), EntityId::new(id)),
843        "entity" => RefTarget::Entity {
844            collection: collection.to_string(),
845            entity_id: EntityId::new(id),
846        },
847        _ => {
848            return Err(RedDBError::Query(format!(
849                "unsupported metadata reference kind '{kind}'"
850            )));
851        }
852    };
853
854    Ok(target)
855}
856
857fn parse_metadata_reference_value(value: &JsonValue) -> RedDBResult<RefTarget> {
858    let JsonValue::Object(object) = value else {
859        return Err(RedDBError::Query(
860            "metadata reference entries must be objects".to_string(),
861        ));
862    };
863    parse_metadata_reference(object)
864}
865
866fn parse_patch_u64_value(value: &JsonValue, field: &str) -> RedDBResult<u64> {
867    let Some(value) = value.as_f64() else {
868        return Err(RedDBError::Query(format!(
869            "field '{field}' must be a number"
870        )));
871    };
872    if value.is_sign_negative() {
873        return Err(RedDBError::Query(format!(
874            "field '{field}' cannot be negative"
875        )));
876    }
877    if value.fract().abs() > f64::EPSILON {
878        return Err(RedDBError::Query(format!(
879            "field '{field}' must be an integer"
880        )));
881    }
882    if value > u64::MAX as f64 {
883        return Err(RedDBError::Query(format!("field '{field}' is too large")));
884    }
885    Ok(value as u64)
886}
887
888fn parse_patch_f32_vector(value: &JsonValue, field: &str) -> RedDBResult<Vec<f32>> {
889    let values = value
890        .as_array()
891        .ok_or_else(|| RedDBError::Query(format!("field '{field}' must be an array")))?;
892    let mut out = Vec::with_capacity(values.len());
893    for value in values {
894        let number = value.as_f64().ok_or_else(|| {
895            RedDBError::Query(format!("field '{field}' must contain only numbers"))
896        })?;
897        out.push(number as f32);
898    }
899    if out.is_empty() {
900        return Err(RedDBError::Query(format!(
901            "field '{field}' cannot be empty"
902        )));
903    }
904    Ok(out)
905}
906
907fn parse_sparse_index_array(value: &JsonValue, field: &str) -> RedDBResult<Vec<u32>> {
908    let values = value
909        .as_array()
910        .ok_or_else(|| RedDBError::Query(format!("field '{field}' must be an array")))?;
911    let mut out = Vec::with_capacity(values.len());
912    for value in values {
913        let value = value.as_f64().ok_or_else(|| {
914            RedDBError::Query(format!("field '{field}' must contain only integers"))
915        })?;
916        if value.is_sign_negative() || value.fract().abs() > f64::EPSILON {
917            return Err(RedDBError::Query(format!(
918                "field '{field}' must contain only u32 values"
919            )));
920        }
921        if value > u32::MAX as f64 {
922            return Err(RedDBError::Query(format!(
923                "field '{field}' value is too large"
924            )));
925        }
926        out.push(value as u32);
927    }
928    Ok(out)
929}
930
931fn parse_sparse_value_array(value: &JsonValue, field: &str) -> RedDBResult<Vec<f32>> {
932    parse_patch_f32_vector(value, field)
933}
934
935fn parse_sparse_vector_value(value: &JsonValue) -> RedDBResult<Option<SparseVector>> {
936    match value {
937        JsonValue::Null => Ok(None),
938        JsonValue::Object(object) => {
939            let indices = parse_sparse_index_array(
940                object.get("indices").ok_or_else(|| {
941                    RedDBError::Query("sparse metadata requires 'indices'".to_string())
942                })?,
943                "sparse.indices",
944            )?;
945            let values = parse_sparse_value_array(
946                object.get("values").ok_or_else(|| {
947                    RedDBError::Query("sparse metadata requires 'values'".to_string())
948                })?,
949                "sparse.values",
950            )?;
951            if indices.len() != values.len() {
952                return Err(RedDBError::Query(
953                    "sparse indices and values lengths must match".to_string(),
954                ));
955            }
956            let dimension = match object.get("dimension").and_then(JsonValue::as_f64) {
957                Some(value) => {
958                    if value.is_sign_negative() || value.fract().abs() > f64::EPSILON {
959                        return Err(RedDBError::Query(
960                            "sparse dimension must be a non-negative integer".to_string(),
961                        ));
962                    }
963                    if value > usize::MAX as f64 {
964                        return Err(RedDBError::Query(
965                            "sparse dimension is too large".to_string(),
966                        ));
967                    }
968                    value as usize
969                }
970                None => indices
971                    .iter()
972                    .max()
973                    .map_or(0, |index| (*index as usize) + 1),
974            };
975            if indices.iter().any(|index| (*index as usize) >= dimension) {
976                return Err(RedDBError::Query(
977                    "sparse indices must be smaller than dimension".to_string(),
978                ));
979            }
980            Ok(Some(SparseVector::new(indices, values, dimension)))
981        }
982        _ => Err(RedDBError::Query(
983            "field 'sparse' must be an object or null".to_string(),
984        )),
985    }
986}
987
988fn apply_patch_json_set(
989    target: &mut JsonValue,
990    path: &[String],
991    value: JsonValue,
992) -> Result<(), String> {
993    if path.is_empty() {
994        return Err("patch path cannot be empty".to_string());
995    }
996
997    let mut current = target;
998    for segment in &path[..path.len() - 1] {
999        let JsonValue::Object(object) = current else {
1000            return Err("patch path target must be an object".to_string());
1001        };
1002        let value = object
1003            .entry(segment.clone())
1004            .or_insert_with(|| JsonValue::Object(Map::new()));
1005        if !matches!(value, JsonValue::Object(_)) {
1006            *value = JsonValue::Object(Map::new());
1007        }
1008        current = value;
1009    }
1010
1011    let JsonValue::Object(object) = current else {
1012        return Err("patch path target must be an object".to_string());
1013    };
1014    object.insert(path[path.len() - 1].clone(), value);
1015    Ok(())
1016}
1017
1018fn apply_patch_json_unset(target: &mut JsonValue, path: &[String]) -> Result<(), String> {
1019    if path.is_empty() {
1020        return Err("patch path cannot be empty".to_string());
1021    }
1022
1023    if path.len() == 1 {
1024        let JsonValue::Object(object) = target else {
1025            return Err("patch path target must be an object".to_string());
1026        };
1027        object.remove(&path[0]);
1028        return Ok(());
1029    }
1030
1031    let mut current = target;
1032    for segment in &path[..path.len() - 1] {
1033        let Some(value) = (match current {
1034            JsonValue::Object(object) => object.get_mut(segment),
1035            _ => {
1036                return Err("patch path target must be an object".to_string());
1037            }
1038        }) else {
1039            return Ok(());
1040        };
1041
1042        if !matches!(value, JsonValue::Object(_)) {
1043            return Ok(());
1044        }
1045        current = value;
1046    }
1047
1048    let JsonValue::Object(object) = current else {
1049        return Err("patch path target must be an object".to_string());
1050    };
1051    object.remove(&path[path.len() - 1]);
1052    Ok(())
1053}
1054
1055fn format_mac(bytes: &[u8; 6]) -> String {
1056    bytes
1057        .iter()
1058        .map(|byte| format!("{byte:02x}"))
1059        .collect::<Vec<_>>()
1060        .join(":")
1061}
1062
1063#[cfg(test)]
1064mod damage_vector_tests {
1065    use super::*;
1066
1067    fn s(n: &str) -> String {
1068        n.to_string()
1069    }
1070
1071    #[test]
1072    fn identical_rows_produce_empty_vector() {
1073        let old = vec![
1074            (s("name"), Value::text(s("alice"))),
1075            (s("age"), Value::Integer(30)),
1076        ];
1077        let new = old.clone();
1078        let dv = row_damage_vector(&old, &new);
1079        assert!(dv.is_empty());
1080        assert!(dv.touched_columns().is_empty());
1081    }
1082
1083    #[test]
1084    fn detects_changed_column_only() {
1085        let old = vec![
1086            (s("name"), Value::text(s("alice"))),
1087            (s("age"), Value::Integer(30)),
1088        ];
1089        let new = vec![
1090            (s("name"), Value::text(s("alice"))),
1091            (s("age"), Value::Integer(31)),
1092        ];
1093        let dv = row_damage_vector(&old, &new);
1094        assert_eq!(dv.changed.len(), 1);
1095        assert_eq!(dv.changed[0].0, "age");
1096        assert!(dv.added.is_empty());
1097        assert!(dv.removed.is_empty());
1098        assert_eq!(dv.touched_columns(), vec!["age"]);
1099    }
1100
1101    #[test]
1102    fn detects_added_and_removed_columns() {
1103        let old = vec![
1104            (s("name"), Value::text(s("alice"))),
1105            (s("nickname"), Value::text(s("al"))),
1106        ];
1107        let new = vec![
1108            (s("name"), Value::text(s("alice"))),
1109            (s("email"), Value::text(s("a@x.com"))),
1110        ];
1111        let dv = row_damage_vector(&old, &new);
1112        assert!(dv.changed.is_empty());
1113        assert_eq!(dv.added.len(), 1);
1114        assert_eq!(dv.added[0].0, "email");
1115        assert_eq!(dv.removed.len(), 1);
1116        assert_eq!(dv.removed[0].0, "nickname");
1117    }
1118
1119    #[test]
1120    fn field_order_does_not_affect_diff() {
1121        // `(name, age)` and `(age, name)` with identical values should
1122        // diff as empty — column order is a presentation concern.
1123        let old = vec![
1124            (s("name"), Value::text(s("bob"))),
1125            (s("age"), Value::Integer(42)),
1126        ];
1127        let new = vec![
1128            (s("age"), Value::Integer(42)),
1129            (s("name"), Value::text(s("bob"))),
1130        ];
1131        assert!(row_damage_vector(&old, &new).is_empty());
1132    }
1133
1134    #[test]
1135    fn mixed_changed_added_removed() {
1136        let old = vec![
1137            (s("a"), Value::Integer(1)),
1138            (s("b"), Value::Integer(2)),
1139            (s("gone"), Value::text(s("x"))),
1140        ];
1141        let new = vec![
1142            (s("a"), Value::Integer(10)),     // changed
1143            (s("b"), Value::Integer(2)),      // unchanged
1144            (s("new"), Value::Boolean(true)), // added
1145        ];
1146        let dv = row_damage_vector(&old, &new);
1147        assert_eq!(dv.changed.len(), 1);
1148        assert_eq!(dv.added.len(), 1);
1149        assert_eq!(dv.removed.len(), 1);
1150        let mut touched: Vec<&str> = dv.touched_columns();
1151        touched.sort();
1152        assert_eq!(touched, vec!["a", "gone", "new"]);
1153    }
1154}