1use std::collections::HashMap;
7use std::sync::Arc;
8
9use reddb_types::Value;
10
11pub const FIRST_USER_ENTITY_ID: u64 = 1024;
23
24pub use super::entity_id::EntityId;
25
26#[derive(Debug, Clone, PartialEq, Eq, Hash)]
28pub enum EntityKind {
29 TableRow { table: Arc<str>, row_id: u64 },
31 GraphNode(Box<GraphNodeKind>),
33 GraphEdge(Box<GraphEdgeKind>),
35 Vector { collection: String },
37 TimeSeriesPoint(Box<TimeSeriesPointKind>),
39 QueueMessage { queue: String, position: u64 },
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Hash)]
44pub struct GraphNodeKind {
45 pub label: String,
46 pub node_type: String,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Hash)]
50pub struct GraphEdgeKind {
51 pub label: String,
52 pub from_node: String,
53 pub to_node: String,
54 pub weight: u32,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq, Hash)]
58pub struct TimeSeriesPointKind {
59 pub series: String,
60 pub metric: String,
61}
62
63impl EntityKind {
64 pub fn storage_type(&self) -> &'static str {
66 match self {
67 Self::TableRow { .. } => "table",
68 Self::GraphNode(_) => "graph_node",
69 Self::GraphEdge(_) => "graph_edge",
70 Self::Vector { .. } => "vector",
71 Self::TimeSeriesPoint(_) => "timeseries",
72 Self::QueueMessage { .. } => "queue",
73 }
74 }
75
76 pub fn collection(&self) -> &str {
78 match self {
79 Self::TableRow { table, .. } => table,
80 Self::GraphNode(n) => &n.label,
81 Self::GraphEdge(e) => &e.label,
82 Self::Vector { collection } => collection,
83 Self::TimeSeriesPoint(ts) => &ts.series,
84 Self::QueueMessage { queue, .. } => queue,
85 }
86 }
87}
88
89#[derive(Debug, Clone)]
91pub enum EntityData {
92 Row(RowData),
94 Node(NodeData),
96 Edge(EdgeData),
98 Vector(VectorData),
100 TimeSeries(TimeSeriesData),
102 QueueMessage(QueueMessageData),
104}
105
106impl EntityData {
107 pub fn is_row(&self) -> bool {
109 matches!(self, Self::Row(_))
110 }
111
112 pub fn is_node(&self) -> bool {
114 matches!(self, Self::Node(_))
115 }
116
117 pub fn is_edge(&self) -> bool {
119 matches!(self, Self::Edge(_))
120 }
121
122 pub fn is_vector(&self) -> bool {
124 matches!(self, Self::Vector(_))
125 }
126
127 pub fn as_row(&self) -> Option<&RowData> {
129 match self {
130 Self::Row(r) => Some(r),
131 _ => None,
132 }
133 }
134
135 pub fn as_node(&self) -> Option<&NodeData> {
137 match self {
138 Self::Node(n) => Some(n),
139 _ => None,
140 }
141 }
142
143 pub fn as_edge(&self) -> Option<&EdgeData> {
145 match self {
146 Self::Edge(e) => Some(e),
147 _ => None,
148 }
149 }
150
151 pub fn as_vector(&self) -> Option<&VectorData> {
153 match self {
154 Self::Vector(v) => Some(v),
155 _ => None,
156 }
157 }
158}
159
160#[derive(Debug, Clone)]
162pub struct RowData {
163 pub columns: Vec<Value>,
165 pub named: Option<HashMap<String, Value>>,
167 pub schema: Option<std::sync::Arc<Vec<String>>>,
171}
172
173impl RowData {
174 pub fn new(columns: Vec<Value>) -> Self {
176 Self {
177 columns,
178 named: None,
179 schema: None,
180 }
181 }
182
183 pub fn with_names(columns: Vec<Value>, names: Vec<String>) -> Self {
185 let named: HashMap<String, Value> =
186 names.into_iter().zip(columns.iter().cloned()).collect();
187 Self {
188 columns,
189 named: Some(named),
190 schema: None,
191 }
192 }
193
194 #[cfg(feature = "full")]
197 pub(crate) fn compact_with_schema(&mut self, schema: &std::sync::Arc<Vec<String>>) -> bool {
198 let Some(named) = &self.named else {
199 return false;
200 };
201 if named.len() != schema.len() || schema.iter().any(|name| !named.contains_key(name)) {
202 return false;
203 }
204 if !self.columns.is_empty()
207 && (self.columns.len() != schema.len()
208 || schema
209 .iter()
210 .zip(&self.columns)
211 .any(|(name, value)| named.get(name) != Some(value)))
212 {
213 return false;
214 }
215 let mut named = self.named.take().expect("validated named row");
216 self.columns = schema
217 .iter()
218 .map(|name| named.remove(name).expect("validated schema field"))
219 .collect();
220 self.schema = Some(std::sync::Arc::clone(schema));
221 true
222 }
223
224 pub fn get_field(&self, name: &str) -> Option<&Value> {
226 if let Some(ref named) = self.named {
228 return named.get(name);
229 }
230 if let Some(ref schema) = self.schema {
232 if let Some(idx) = schema.iter().position(|s| s == name) {
233 return self.columns.get(idx);
234 }
235 }
236 None
237 }
238
239 pub fn iter_fields(&self) -> Box<dyn Iterator<Item = (&str, &Value)> + '_> {
241 if let Some(ref named) = self.named {
242 Box::new(named.iter().map(|(k, v)| (k.as_str(), v)))
243 } else if let Some(ref schema) = self.schema {
244 Box::new(
245 schema
246 .iter()
247 .zip(self.columns.iter())
248 .map(|(k, v)| (k.as_str(), v)),
249 )
250 } else {
251 Box::new(std::iter::empty())
252 }
253 }
254
255 pub fn get(&self, index: usize) -> Option<&Value> {
257 self.columns.get(index)
258 }
259
260 pub fn get_by_name(&self, name: &str) -> Option<&Value> {
262 self.named.as_ref()?.get(name)
263 }
264
265 pub fn len(&self) -> usize {
267 self.columns.len()
268 }
269
270 pub fn is_empty(&self) -> bool {
272 self.columns.is_empty()
273 }
274}
275
276#[derive(Debug, Clone)]
278pub struct NodeData {
279 pub properties: HashMap<String, Value>,
281}
282
283impl NodeData {
284 pub fn new() -> Self {
286 Self {
287 properties: HashMap::new(),
288 }
289 }
290
291 pub fn with_properties(properties: HashMap<String, Value>) -> Self {
293 Self { properties }
294 }
295
296 pub fn set(&mut self, key: impl Into<String>, value: Value) {
298 self.properties.insert(key.into(), value);
299 }
300
301 pub fn get(&self, key: &str) -> Option<&Value> {
303 self.properties.get(key)
304 }
305
306 pub fn has(&self, key: &str) -> bool {
308 self.properties.contains_key(key)
309 }
310}
311
312impl Default for NodeData {
313 fn default() -> Self {
314 Self::new()
315 }
316}
317
318#[derive(Debug, Clone)]
320pub struct EdgeData {
321 pub properties: HashMap<String, Value>,
323 pub weight: f32,
325}
326
327impl EdgeData {
328 pub fn new(weight: f32) -> Self {
330 Self {
331 properties: HashMap::new(),
332 weight,
333 }
334 }
335
336 pub fn with_properties(weight: f32, properties: HashMap<String, Value>) -> Self {
338 Self { properties, weight }
339 }
340
341 pub fn set(&mut self, key: impl Into<String>, value: Value) {
343 self.properties.insert(key.into(), value);
344 }
345
346 pub fn get(&self, key: &str) -> Option<&Value> {
348 self.properties.get(key)
349 }
350}
351
352impl Default for EdgeData {
353 fn default() -> Self {
354 Self::new(1.0)
355 }
356}
357
358#[derive(Debug, Clone)]
360pub struct VectorData {
361 pub dense: Vec<f32>,
363 pub sparse: Option<SparseVector>,
365 pub content: Option<String>,
367}
368
369impl VectorData {
370 pub fn new(dense: Vec<f32>) -> Self {
372 Self {
373 dense,
374 sparse: None,
375 content: None,
376 }
377 }
378
379 pub fn with_sparse(dense: Vec<f32>, sparse: SparseVector) -> Self {
381 Self {
382 dense,
383 sparse: Some(sparse),
384 content: None,
385 }
386 }
387
388 pub fn with_content(mut self, content: impl Into<String>) -> Self {
390 self.content = Some(content.into());
391 self
392 }
393
394 pub fn dimension(&self) -> usize {
396 self.dense.len()
397 }
398
399 pub fn is_hybrid(&self) -> bool {
401 self.sparse.is_some()
402 }
403}
404
405#[derive(Debug, Clone)]
407pub struct TimeSeriesData {
408 pub metric: String,
410 pub series_id: Option<u64>,
412 pub timestamp_ns: u64,
414 pub value: f64,
416 pub tags: std::collections::HashMap<String, String>,
418 pub fields: std::collections::HashMap<String, Value>,
420}
421
422#[derive(Debug, Clone)]
424pub struct QueueMessageData {
425 pub payload: Value,
427 pub priority: Option<i32>,
429 pub enqueued_at_ns: u64,
431 pub attempts: u32,
433 pub max_attempts: u32,
435 pub acked: bool,
437}
438
439#[derive(Debug, Clone)]
441pub struct SparseVector {
442 pub indices: Vec<u32>,
444 pub values: Vec<f32>,
446 pub dimension: usize,
448}
449
450impl SparseVector {
451 pub fn new(indices: Vec<u32>, values: Vec<f32>, dimension: usize) -> Self {
453 debug_assert_eq!(indices.len(), values.len());
454 Self {
455 indices,
456 values,
457 dimension,
458 }
459 }
460
461 pub fn nnz(&self) -> usize {
463 self.indices.len()
464 }
465
466 pub fn sparsity(&self) -> f32 {
468 if self.dimension == 0 {
469 1.0
470 } else {
471 1.0 - (self.nnz() as f32 / self.dimension as f32)
472 }
473 }
474
475 pub fn get(&self, index: u32) -> f32 {
477 self.indices
478 .iter()
479 .position(|&i| i == index)
480 .map(|pos| self.values[pos])
481 .unwrap_or(0.0)
482 }
483}
484
485#[derive(Debug, Clone)]
487pub struct EmbeddingSlot {
488 pub name: String,
490 pub vector: Vec<f32>,
492 pub model: String,
494 pub dimension: usize,
496 pub generated_at: u64,
498}
499
500use crate::clock::current_unix_secs;
501
502impl EmbeddingSlot {
503 pub fn new(name: impl Into<String>, vector: Vec<f32>, model: impl Into<String>) -> Self {
505 let dimension = vector.len();
506 Self {
507 name: name.into(),
508 vector,
509 model: model.into(),
510 dimension,
511 generated_at: current_unix_secs(),
512 }
513 }
514}
515
516#[derive(Debug, Clone)]
518pub struct UnifiedEntity {
519 pub id: EntityId,
521 logical_id: Option<EntityId>,
525 pub kind: EntityKind,
527 pub created_at: u64,
529 pub updated_at: u64,
531 pub data: EntityData,
533 pub sequence_id: u64,
535 pub field_bloom: u64,
546 pub xmin: u64,
555 pub xmax: u64,
561 aux: Option<Box<EntityAux>>,
564}
565
566#[derive(Debug, Clone, Default)]
568pub struct EntityAux {
569 pub embeddings: Vec<EmbeddingSlot>,
571 pub cross_refs: Vec<CrossRef>,
573}
574
575impl UnifiedEntity {
576 pub fn canonicalize_system_collection_names(&mut self) {
580 match &mut self.kind {
581 EntityKind::TableRow { table, .. } => {
582 if let Some(canonical) = super::system_collection_names::canonical_name(table) {
583 *table = Arc::from(canonical);
584 }
585 }
586 EntityKind::Vector { collection } => {
587 if let Some(canonical) = super::system_collection_names::canonical_name(collection)
588 {
589 *collection = canonical.to_owned();
590 }
591 }
592 EntityKind::TimeSeriesPoint(point) => {
593 if let Some(canonical) =
594 super::system_collection_names::canonical_name(&point.series)
595 {
596 point.series = canonical.to_owned();
597 }
598 }
599 EntityKind::QueueMessage { queue, .. } => {
600 if let Some(canonical) = super::system_collection_names::canonical_name(queue) {
601 *queue = canonical.to_owned();
602 }
603 }
604 EntityKind::GraphNode(_) | EntityKind::GraphEdge(_) => {}
605 }
606 if let Some(aux) = &mut self.aux {
607 for reference in &mut aux.cross_refs {
608 if let Some(canonical) =
609 super::system_collection_names::canonical_name(&reference.target_collection)
610 {
611 reference.target_collection = canonical.to_owned();
612 }
613 }
614 }
615 }
616
617 pub fn embeddings(&self) -> &[EmbeddingSlot] {
619 self.aux
620 .as_ref()
621 .map(|a| a.embeddings.as_slice())
622 .unwrap_or(&[])
623 }
624
625 pub fn cross_refs(&self) -> &[CrossRef] {
627 self.aux
628 .as_ref()
629 .map(|a| a.cross_refs.as_slice())
630 .unwrap_or(&[])
631 }
632
633 pub fn embeddings_mut(&mut self) -> &mut Vec<EmbeddingSlot> {
635 &mut self.aux.get_or_insert_with(Default::default).embeddings
636 }
637
638 pub fn cross_refs_mut(&mut self) -> &mut Vec<CrossRef> {
640 &mut self.aux.get_or_insert_with(Default::default).cross_refs
641 }
642
643 pub fn has_aux(&self) -> bool {
645 self.aux.is_some()
646 }
647}
648
649#[inline]
655pub fn field_name_bloom(name: &str) -> u64 {
656 let b = name.as_bytes();
657 if b.is_empty() {
658 return 0;
659 }
660 1u64 << (b[b.len() / 2] & 63)
661}
662
663pub fn compute_entity_field_bloom(data: &EntityData) -> u64 {
667 match data {
668 EntityData::Row(row) => {
669 if row.schema.is_some() {
670 return 0;
673 }
674 if let Some(named) = &row.named {
675 let mut bloom = named.keys().fold(0u64, |acc, k| acc | field_name_bloom(k));
676 if let Some(Value::Json(bytes)) = named.get("body") {
684 if let Ok(names) = reddb_types::document_body_codec::field_names(bytes) {
685 for name in names {
686 bloom |= field_name_bloom(&name);
687 }
688 }
689 }
690 bloom
691 } else {
692 0
693 }
694 }
695 EntityData::Node(node) => node
696 .properties
697 .keys()
698 .fold(0u64, |acc, k| acc | field_name_bloom(k)),
699 EntityData::Edge(edge) => edge
700 .properties
701 .keys()
702 .fold(0u64, |acc, k| acc | field_name_bloom(k)),
703 _ => 0,
705 }
706}
707
708impl UnifiedEntity {
709 pub fn new(id: EntityId, kind: EntityKind, data: EntityData) -> Self {
711 let now = current_unix_secs();
712 let field_bloom = compute_entity_field_bloom(&data);
713
714 Self {
715 id,
716 logical_id: None,
717 kind,
718 created_at: now,
719 updated_at: now,
720 data,
721 sequence_id: 0,
722 field_bloom,
723 xmin: 0,
726 xmax: 0,
727 aux: None,
728 }
729 }
730
731 #[inline]
742 pub fn is_visible(&self, snapshot_xid: u64) -> bool {
743 if self.xmin != 0 && self.xmin > snapshot_xid {
744 return false;
745 }
746 if self.xmax != 0 && self.xmax <= snapshot_xid {
747 return false;
748 }
749 true
750 }
751
752 #[inline]
755 pub fn set_xmin(&mut self, xid: u64) {
756 self.xmin = xid;
757 }
758
759 #[inline]
763 pub fn set_xmax(&mut self, xid: u64) {
764 self.xmax = xid;
765 }
766
767 #[inline]
770 pub fn logical_id(&self) -> EntityId {
771 self.logical_id.unwrap_or(self.id)
772 }
773
774 #[inline]
776 pub fn has_explicit_logical_id(&self) -> bool {
777 self.logical_id.is_some()
778 }
779
780 #[inline]
782 pub fn set_logical_id(&mut self, logical_id: EntityId) {
783 self.logical_id = Some(logical_id);
784 }
785
786 #[inline]
798 pub fn ensure_table_logical_id(&mut self) {
799 if self.logical_id.is_none()
800 && matches!(
801 self.kind,
802 EntityKind::TableRow { .. } | EntityKind::GraphNode(_) | EntityKind::GraphEdge(_)
803 )
804 {
805 self.logical_id = Some(self.id);
806 }
807 }
808
809 pub fn table_row(
811 id: EntityId,
812 table: impl Into<Arc<str>>,
813 row_id: u64,
814 columns: Vec<Value>,
815 ) -> Self {
816 Self::new(
817 id,
818 EntityKind::TableRow {
819 table: table.into(),
820 row_id,
821 },
822 EntityData::Row(RowData::new(columns)),
823 )
824 }
825
826 pub fn graph_node(
828 id: EntityId,
829 label: impl Into<String>,
830 node_type: impl Into<String>,
831 properties: HashMap<String, Value>,
832 ) -> Self {
833 Self::new(
834 id,
835 EntityKind::GraphNode(Box::new(GraphNodeKind {
836 label: label.into(),
837 node_type: node_type.into(),
838 })),
839 EntityData::Node(NodeData::with_properties(properties)),
840 )
841 }
842
843 pub fn graph_edge(
845 id: EntityId,
846 label: impl Into<String>,
847 from: impl Into<String>,
848 to: impl Into<String>,
849 weight: f32,
850 properties: HashMap<String, Value>,
851 ) -> Self {
852 Self::new(
853 id,
854 EntityKind::GraphEdge(Box::new(GraphEdgeKind {
855 label: label.into(),
856 from_node: from.into(),
857 to_node: to.into(),
858 weight: (weight * 1000.0) as u32,
859 })),
860 EntityData::Edge(EdgeData::with_properties(weight, properties)),
861 )
862 }
863
864 pub fn vector(id: EntityId, collection: impl Into<String>, vector: Vec<f32>) -> Self {
866 Self::new(
867 id,
868 EntityKind::Vector {
869 collection: collection.into(),
870 },
871 EntityData::Vector(VectorData::new(vector)),
872 )
873 }
874
875 pub fn add_embedding(&mut self, slot: EmbeddingSlot) {
877 self.embeddings_mut().push(slot);
878 self.touch();
879 }
880
881 pub fn add_cross_ref(&mut self, cross_ref: CrossRef) {
883 self.cross_refs_mut().push(cross_ref);
884 self.touch();
885 }
886
887 pub fn get_embedding(&self, name: &str) -> Option<&EmbeddingSlot> {
889 self.embeddings().iter().find(|e| e.name == name)
890 }
891
892 fn touch(&mut self) {
894 self.updated_at = current_unix_secs();
895 }
896
897 pub fn is_stale(&self, max_age_secs: u64) -> bool {
899 let now = current_unix_secs();
900 now.saturating_sub(self.updated_at) > max_age_secs
901 }
902}
903
904#[derive(Debug, Clone, PartialEq)]
906pub struct CrossRef {
907 pub source: EntityId,
909 pub target: EntityId,
911 pub target_collection: String,
913 pub ref_type: RefType,
915 pub weight: f32,
917 pub created_at: u64,
919}
920
921impl CrossRef {
922 pub fn new(
924 source: EntityId,
925 target: EntityId,
926 target_collection: impl Into<String>,
927 ref_type: RefType,
928 ) -> Self {
929 Self {
930 source,
931 target,
932 target_collection: target_collection.into(),
933 ref_type,
934 weight: 1.0,
935 created_at: current_unix_secs(),
936 }
937 }
938
939 pub fn with_weight(
941 source: EntityId,
942 target: EntityId,
943 target_collection: impl Into<String>,
944 ref_type: RefType,
945 weight: f32,
946 ) -> Self {
947 let mut cr = Self::new(source, target, target_collection, ref_type);
948 cr.weight = weight;
949 cr
950 }
951}
952
953#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
955pub enum RefType {
956 RowToNode, RowToEdge, NodeToRow, RowToVector, VectorToRow, NodeToVector, EdgeToVector, VectorToNode, SimilarTo, RelatedTo, DerivesFrom, Mentions, Contains, DependsOn, }
978
979impl RefType {
980 pub fn inverse(&self) -> Option<Self> {
982 match self {
983 Self::RowToNode => Some(Self::NodeToRow),
984 Self::NodeToRow => Some(Self::RowToNode),
985 Self::RowToVector => Some(Self::VectorToRow),
986 Self::VectorToRow => Some(Self::RowToVector),
987 Self::NodeToVector => Some(Self::VectorToNode),
988 Self::VectorToNode => Some(Self::NodeToVector),
989 Self::SimilarTo => Some(Self::SimilarTo), Self::RelatedTo => Some(Self::RelatedTo), _ => None, }
993 }
994
995 pub fn is_symmetric(&self) -> bool {
997 matches!(self, Self::SimilarTo | Self::RelatedTo)
998 }
999
1000 pub fn to_byte(&self) -> u8 {
1002 match self {
1003 Self::RowToNode => 0,
1004 Self::RowToEdge => 1,
1005 Self::NodeToRow => 2,
1006 Self::RowToVector => 3,
1007 Self::VectorToRow => 4,
1008 Self::NodeToVector => 5,
1009 Self::EdgeToVector => 6,
1010 Self::VectorToNode => 7,
1011 Self::SimilarTo => 8,
1012 Self::RelatedTo => 9,
1013 Self::DerivesFrom => 10,
1014 Self::Mentions => 11,
1015 Self::Contains => 12,
1016 Self::DependsOn => 13,
1017 }
1018 }
1019
1020 pub fn from_byte(byte: u8) -> Self {
1022 match byte {
1023 0 => Self::RowToNode,
1024 1 => Self::RowToEdge,
1025 2 => Self::NodeToRow,
1026 3 => Self::RowToVector,
1027 4 => Self::VectorToRow,
1028 5 => Self::NodeToVector,
1029 6 => Self::EdgeToVector,
1030 7 => Self::VectorToNode,
1031 8 => Self::SimilarTo,
1032 9 => Self::RelatedTo,
1033 10 => Self::DerivesFrom,
1034 11 => Self::Mentions,
1035 12 => Self::Contains,
1036 13 => Self::DependsOn,
1037 _ => Self::RelatedTo, }
1039 }
1040}
1041
1042impl From<Vec<Value>> for RowData {
1044 fn from(columns: Vec<Value>) -> Self {
1045 RowData::new(columns)
1046 }
1047}
1048
1049impl From<HashMap<String, Value>> for NodeData {
1051 fn from(properties: HashMap<String, Value>) -> Self {
1052 NodeData::with_properties(properties)
1053 }
1054}
1055
1056impl From<Vec<f32>> for VectorData {
1058 fn from(dense: Vec<f32>) -> Self {
1059 VectorData::new(dense)
1060 }
1061}
1062
1063impl From<(Vec<f32>, SparseVector)> for VectorData {
1065 fn from((dense, sparse): (Vec<f32>, SparseVector)) -> Self {
1066 VectorData::with_sparse(dense, sparse)
1067 }
1068}
1069
1070impl UnifiedEntity {
1072 pub fn from_properties(
1074 id: EntityId,
1075 label: impl Into<String>,
1076 node_type: impl Into<String>,
1077 properties: impl IntoIterator<Item = (impl Into<String>, Value)>,
1078 ) -> Self {
1079 let props: HashMap<String, Value> =
1080 properties.into_iter().map(|(k, v)| (k.into(), v)).collect();
1081 Self::graph_node(id, label, node_type, props)
1082 }
1083
1084 pub fn into_row(self) -> Option<RowData> {
1086 match self.data {
1087 EntityData::Row(r) => Some(r),
1088 _ => None,
1089 }
1090 }
1091
1092 pub fn into_node(self) -> Option<NodeData> {
1094 match self.data {
1095 EntityData::Node(n) => Some(n),
1096 _ => None,
1097 }
1098 }
1099
1100 pub fn into_edge(self) -> Option<EdgeData> {
1102 match self.data {
1103 EntityData::Edge(e) => Some(e),
1104 _ => None,
1105 }
1106 }
1107
1108 pub fn into_vector(self) -> Option<VectorData> {
1110 match self.data {
1111 EntityData::Vector(v) => Some(v),
1112 _ => None,
1113 }
1114 }
1115}
1116
1117#[cfg(test)]
1118mod tests {
1119 use super::*;
1120
1121 #[test]
1122 fn test_entity_creation() {
1123 let id = EntityId::new(1);
1124 let entity = UnifiedEntity::table_row(
1125 id,
1126 "users",
1127 100,
1128 vec![Value::text("alice".to_string()), Value::Integer(25)],
1129 );
1130
1131 assert!(entity.data.is_row());
1132 assert_eq!(entity.kind.storage_type(), "table");
1133 assert_eq!(entity.kind.collection(), "users");
1134 }
1135
1136 #[test]
1137 fn test_cross_refs() {
1138 let id1 = EntityId::new(1);
1139 let id2 = EntityId::new(2);
1140
1141 let cross_ref = CrossRef::new(id1, id2, "nodes", RefType::RowToNode);
1142 assert_eq!(cross_ref.source, id1);
1143 assert_eq!(cross_ref.target, id2);
1144 assert_eq!(cross_ref.ref_type.inverse(), Some(RefType::NodeToRow));
1145 }
1146
1147 #[test]
1148 fn test_sparse_vector() {
1149 let sparse = SparseVector::new(vec![0, 5, 10], vec![1.0, 2.0, 3.0], 100);
1150
1151 assert_eq!(sparse.nnz(), 3);
1152 assert_eq!(sparse.get(5), 2.0);
1153 assert_eq!(sparse.get(3), 0.0);
1154 assert!(sparse.sparsity() > 0.9);
1155 }
1156
1157 #[test]
1158 fn test_embedding_slots() {
1159 let mut entity = UnifiedEntity::table_row(
1160 EntityId::new(1),
1161 "documents",
1162 1,
1163 vec![Value::text("Hello world".to_string())],
1164 );
1165
1166 entity.add_embedding(EmbeddingSlot::new(
1167 "content",
1168 vec![0.1, 0.2, 0.3],
1169 "text-embedding-3-small",
1170 ));
1171
1172 assert_eq!(entity.embeddings().len(), 1);
1173 assert!(entity.get_embedding("content").is_some());
1174 assert!(entity.get_embedding("summary").is_none());
1175 }
1176}