audb-runtime 0.1.11

Runtime library for AuDB database applications with Manifold backend
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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
//! Database connection and query execution with Manifold backend
//!
//! This module provides the `Database` type for managing Manifold database connections
//! and executing queries. Each database uses Manifold's ColumnFamilyDatabase for
//! multi-tenant storage with concurrent write support.

use crate::error::{QueryError, Result};
use crate::types::QueryResult;
use manifold::column_family::ColumnFamilyDatabase;
use manifold_graph::{GraphTable, GraphTableRead};
use manifold_properties::{PropertyTable, PropertyTableRead, PropertyValue};
use manifold_vectors::{VectorTable, VectorTableRead};
use std::path::{Path, PathBuf};
use uuid::Uuid;

/// Database connection wrapper
///
/// Wraps a Manifold ColumnFamilyDatabase and provides query execution methods.
/// This is the main entry point for generated code.
///
/// ## Architecture
///
/// - Each schema becomes a column family in Manifold
/// - Properties stored via manifold-properties (typed, temporal)
/// - Relationships stored via manifold-graph (bidirectional edges)
/// - Vectors stored via manifold-vectors (zero-copy access)
///
/// ## Thread Safety
///
/// Database is `Send + Sync` and can be shared across async tasks.
pub struct Database {
    /// Path to the database
    path: PathBuf,

    /// Manifold column family database
    cf_db: ColumnFamilyDatabase,
}

impl Database {
    /// Open a database connection
    ///
    /// Creates or opens a Manifold database at the specified path.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # use audb_runtime::Database;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let db = Database::open("./data/app.manifold").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path = path.as_ref().to_path_buf();

        // Ensure parent directory exists
        if let Some(parent) = path.parent() {
            if !parent.exists() {
                std::fs::create_dir_all(parent).map_err(|e| QueryError::ConnectionError {
                    message: format!("Failed to create parent directory: {}", e),
                })?;
            }
        }

        // Open Manifold ColumnFamilyDatabase (creates file if it doesn't exist)
        let cf_db = ColumnFamilyDatabase::builder().open(&path).map_err(|e| {
            QueryError::ConnectionError {
                message: format!("Failed to open Manifold database: {}", e),
            }
        })?;

        Ok(Self { path, cf_db })
    }

    /// Close the database connection
    ///
    /// Explicitly closes the connection and flushes any pending writes.
    /// The database is automatically closed when dropped.
    pub async fn close(self) -> Result<()> {
        // Manifold handles cleanup on drop
        drop(self.cf_db);
        Ok(())
    }

    /// Get the database path
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Get a collection (column family) for a schema
    ///
    /// This is the primary method used by generated code to access schema storage.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # use audb_runtime::Database;
    /// # async fn example(db: &Database) -> Result<(), Box<dyn std::error::Error>> {
    /// let users_collection = db.collection("users")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn collection(&self, name: &str) -> Result<Collection> {
        let cf =
            self.cf_db
                .column_family_or_create(name)
                .map_err(|e| QueryError::ConnectionError {
                    message: format!("Failed to get column family '{}': {}", name, e),
                })?;

        Ok(Collection { cf })
    }

    /// Execute a HyperQL query (stub for now)
    ///
    /// This will be implemented when HyperQL compiler is integrated.
    pub async fn execute_hyperql(&self, _query: &str) -> Result<QueryResult> {
        // TODO: Implement HyperQL query compilation and execution
        Ok(QueryResult {
            rows: Vec::new(),
            affected_rows: 0,
        })
    }

    /// Execute a SQL query (stub for now)
    pub async fn execute_sql(&self, _query: &str) -> Result<QueryResult> {
        // TODO: Implement SQL query execution
        Ok(QueryResult {
            rows: Vec::new(),
            affected_rows: 0,
        })
    }

    /// Execute a Cypher query (stub for now)
    pub async fn execute_cypher(&self, _query: &str) -> Result<QueryResult> {
        // TODO: Implement Cypher query execution
        Ok(QueryResult {
            rows: Vec::new(),
            affected_rows: 0,
        })
    }

    /// Execute a custom language query
    pub async fn execute_custom(&self, language: &str, query: &str) -> Result<QueryResult> {
        match language {
            "hyperql" => self.execute_hyperql(query).await,
            "sql" => self.execute_sql(query).await,
            "cypher" => self.execute_cypher(query).await,
            _ => Err(QueryError::UnsupportedLanguage {
                language: language.to_string(),
            }),
        }
    }
}

/// Collection wrapper for a schema
///
/// Each collection corresponds to a schema and provides CRUD operations
/// backed by Manifold's PropertyTable and GraphTable.
pub struct Collection {
    cf: manifold::column_family::ColumnFamily,
}

impl Collection {
    /// Create an entity in the collection
    ///
    /// Stores entity properties in PropertyTable with native types and temporal tracking.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # use audb_runtime::Database;
    /// # use uuid::Uuid;
    /// # use serde_json::json;
    /// # async fn example(db: &Database) -> Result<(), Box<dyn std::error::Error>> {
    /// let collection = db.collection("users")?;
    /// let id = Uuid::new_v4();
    /// let data = json!({
    ///     "name": "Alice",
    ///     "age": 42,
    ///     "active": true
    /// });
    /// collection.create_entity(id, data)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn create_entity(&self, id: Uuid, data: serde_json::Value) -> Result<()> {
        let write_txn = self
            .cf
            .begin_write()
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to begin transaction: {}", e),
            })?;

        let mut props = PropertyTable::open(&write_txn, "properties").map_err(|e| {
            QueryError::ExecutionError {
                message: format!("Failed to open PropertyTable: {}", e),
            }
        })?;

        // Convert JSON to properties
        if let serde_json::Value::Object(map) = data {
            for (key, value) in map {
                let prop_value = match value {
                    serde_json::Value::Number(n) if n.is_i64() => {
                        PropertyValue::new_integer(n.as_i64().unwrap())
                    }
                    serde_json::Value::Number(n) if n.is_f64() => {
                        PropertyValue::new_float(n.as_f64().unwrap())
                    }
                    serde_json::Value::Bool(b) => PropertyValue::new_boolean(b),
                    serde_json::Value::String(s) => PropertyValue::new_string(s),
                    serde_json::Value::Null => PropertyValue::new_null(),
                    // Store complex types (arrays, objects) as JSON strings
                    _ => PropertyValue::new_string(value.to_string()),
                };

                props.set(&id, key.as_str(), prop_value).map_err(|e| {
                    QueryError::ExecutionError {
                        message: format!("Failed to set property: {}", e),
                    }
                })?;
            }
        }

        drop(props);
        write_txn.commit().map_err(|e| QueryError::ExecutionError {
            message: format!("Failed to commit transaction: {}", e),
        })?;

        Ok(())
    }

    /// Get an entity from the collection
    ///
    /// Returns None if the entity doesn't exist.
    pub fn get_entity(&self, id: Uuid) -> Result<Option<serde_json::Value>> {
        let read_txn = self
            .cf
            .begin_read()
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to begin read transaction: {}", e),
            })?;

        let props = PropertyTableRead::open(&read_txn, "properties").map_err(|e| {
            QueryError::ExecutionError {
                message: format!("Failed to open PropertyTable: {}", e),
            }
        })?;

        // Get all properties for this entity
        let mut map = serde_json::Map::new();
        let properties = props.get_all(&id).map_err(|e| QueryError::ExecutionError {
            message: format!("Failed to read properties: {}", e),
        })?;

        for (key, value_guard) in properties {
            let value = value_guard.value();

            let json_value = if let Some(i) = value.as_integer() {
                serde_json::Value::Number(i.into())
            } else if let Some(f) = value.as_float() {
                serde_json::Number::from_f64(f)
                    .map(serde_json::Value::Number)
                    .unwrap_or(serde_json::Value::Null)
            } else if let Some(b) = value.as_boolean() {
                serde_json::Value::Bool(b)
            } else if let Some(s) = value.as_string() {
                // Try to parse as JSON first (for complex types stored as JSON strings)
                serde_json::from_str(s).unwrap_or_else(|_| serde_json::Value::String(s.to_string()))
            } else {
                serde_json::Value::Null
            };

            map.insert(key.to_string(), json_value);
        }

        if map.is_empty() {
            Ok(None)
        } else {
            Ok(Some(serde_json::Value::Object(map)))
        }
    }

    /// Update an entity in the collection
    ///
    /// Properties are automatically versioned with temporal tracking.
    pub fn update_entity(&self, id: Uuid, data: serde_json::Value) -> Result<()> {
        // Properties are automatically versioned, so update = create
        self.create_entity(id, data)
    }

    /// Delete an entity from the collection
    ///
    /// Removes all properties for the entity (soft delete via temporal tracking).
    pub fn delete_entity(&self, id: Uuid) -> Result<()> {
        let write_txn = self
            .cf
            .begin_write()
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to begin transaction: {}", e),
            })?;

        let mut props = PropertyTable::open(&write_txn, "properties").map_err(|e| {
            QueryError::ExecutionError {
                message: format!("Failed to open PropertyTable: {}", e),
            }
        })?;

        // Read property keys first
        let read_txn = self
            .cf
            .begin_read()
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to begin read transaction: {}", e),
            })?;

        let read_props = PropertyTableRead::open(&read_txn, "properties").map_err(|e| {
            QueryError::ExecutionError {
                message: format!("Failed to open PropertyTable: {}", e),
            }
        })?;

        // Collect property keys to delete
        let keys_to_delete: Vec<String> = read_props
            .get_all(&id)
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to read properties: {}", e),
            })?
            .iter()
            .map(|(key, _)| key.to_string())
            .collect();

        drop(read_props);
        drop(read_txn);

        // Convert to references for bulk delete
        let keys_refs: Vec<(Uuid, &str)> = keys_to_delete
            .iter()
            .map(|key| (id, key.as_str()))
            .collect();

        // Delete properties
        props
            .remove_bulk(&keys_refs)
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to delete properties: {}", e),
            })?;

        drop(props);
        write_txn.commit().map_err(|e| QueryError::ExecutionError {
            message: format!("Failed to commit transaction: {}", e),
        })?;

        Ok(())
    }

    /// Add an edge between two entities
    ///
    /// Creates a bidirectional edge in the GraphTable.
    pub fn add_edge(&self, source: Uuid, edge_type: &str, target: Uuid) -> Result<()> {
        let write_txn = self
            .cf
            .begin_write()
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to begin transaction: {}", e),
            })?;

        let mut graph =
            GraphTable::open(&write_txn, "edges").map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to open GraphTable: {}", e),
            })?;

        graph
            .add_edge(&source, edge_type, &target, true, 1.0, None)
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to add edge: {}", e),
            })?;

        drop(graph);
        write_txn.commit().map_err(|e| QueryError::ExecutionError {
            message: format!("Failed to commit transaction: {}", e),
        })?;

        Ok(())
    }

    /// Get outgoing edges from an entity
    ///
    /// Returns all target UUIDs for edges of the specified type.
    pub fn get_outgoing_edges(&self, source: Uuid, edge_type: &str) -> Result<Vec<Uuid>> {
        let read_txn = self
            .cf
            .begin_read()
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to begin read transaction: {}", e),
            })?;

        let graph =
            GraphTableRead::open(&read_txn, "edges").map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to open GraphTable: {}", e),
            })?;

        let mut targets = Vec::new();
        let edges = graph
            .outgoing_edges(&source)
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to read outgoing edges: {}", e),
            })?;

        for edge_result in edges {
            let edge = edge_result.map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to read edge: {}", e),
            })?;

            if edge.edge_type == edge_type && edge.is_active {
                targets.push(edge.target);
            }
        }

        Ok(targets)
    }

    /// Get incoming edges to an entity
    ///
    /// Returns all source UUIDs for edges of the specified type.
    pub fn get_incoming_edges(&self, target: Uuid, edge_type: &str) -> Result<Vec<Uuid>> {
        let read_txn = self
            .cf
            .begin_read()
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to begin read transaction: {}", e),
            })?;

        let graph =
            GraphTableRead::open(&read_txn, "edges").map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to open GraphTable: {}", e),
            })?;

        let mut sources = Vec::new();
        let edges = graph
            .incoming_edges(&target)
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to read incoming edges: {}", e),
            })?;

        for edge_result in edges {
            let edge = edge_result.map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to read edge: {}", e),
            })?;

            if edge.edge_type == edge_type && edge.is_active {
                sources.push(edge.source);
            }
        }

        Ok(sources)
    }

    /// List all entity IDs in the collection
    ///
    /// Returns a vector of all UUIDs that have properties in this collection.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # use audb_runtime::Database;
    /// # async fn example(db: &Database) -> Result<(), Box<dyn std::error::Error>> {
    /// let collection = db.collection("users")?;
    /// let ids = collection.list_all_ids()?;
    /// println!("Found {} entities", ids.len());
    /// # Ok(())
    /// # }
    /// ```
    pub fn list_all_ids(&self) -> Result<Vec<Uuid>> {
        let read_txn = self
            .cf
            .begin_read()
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to begin read transaction: {}", e),
            })?;

        let props = PropertyTableRead::open(&read_txn, "properties").map_err(|e| {
            QueryError::ExecutionError {
                message: format!("Failed to open PropertyTable: {}", e),
            }
        })?;

        let mut entity_ids = std::collections::HashSet::new();

        // Scan all properties and collect unique entity IDs
        for result in props.iter().map_err(|e| QueryError::ExecutionError {
            message: format!("Failed to iterate properties: {}", e),
        })? {
            let ((entity_id, _key), _value) = result.map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to read property: {}", e),
            })?;
            entity_ids.insert(entity_id);
        }

        Ok(entity_ids.into_iter().collect())
    }

    /// List all entities in the collection
    ///
    /// Returns all entities with their JSON data.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # use audb_runtime::Database;
    /// # async fn example(db: &Database) -> Result<(), Box<dyn std::error::Error>> {
    /// let collection = db.collection("users")?;
    /// let entities = collection.list_all_entities()?;
    /// for (id, data) in entities {
    ///     println!("Entity {}: {:?}", id, data);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn list_all_entities(&self) -> Result<Vec<(Uuid, serde_json::Value)>> {
        let ids = self.list_all_ids()?;
        let mut entities = Vec::new();

        for id in ids {
            if let Some(data) = self.get_entity(id)? {
                entities.push((id, data));
            }
        }

        Ok(entities)
    }

    /// Get a VectorTable for storing and retrieving embeddings
    ///
    /// The dimension is a compile-time const generic, typically provided
    /// by the code generator based on Tessera model metadata.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # use audb_runtime::Database;
    /// # use uuid::Uuid;
    /// # async fn example(db: &Database) -> Result<(), Box<dyn std::error::Error>> {
    /// let collection = db.collection("documents")?;
    /// let vectors = collection.vectors::<384>("embeddings")?;
    ///
    /// let id = Uuid::new_v4();
    /// let embedding = vec![0.1f32; 384];
    /// vectors.insert(&id, &embedding)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn vectors<const DIM: usize>(&self, table_name: &str) -> Result<VectorTableWrapper<DIM>> {
        Ok(VectorTableWrapper {
            cf: self.cf.clone(),
            table_name: table_name.to_string(),
        })
    }
}

/// Wrapper for VectorTable operations
///
/// Provides write and read access to vector embeddings with const generic dimensions.
pub struct VectorTableWrapper<const DIM: usize> {
    cf: manifold::column_family::ColumnFamily,
    table_name: String,
}

impl<const DIM: usize> VectorTableWrapper<DIM> {
    /// Insert a vector for an entity
    pub fn insert(&self, id: &Uuid, vector: &[f32]) -> Result<()> {
        if vector.len() != DIM {
            return Err(QueryError::ExecutionError {
                message: format!(
                    "Vector dimension mismatch: expected {}, got {}",
                    DIM,
                    vector.len()
                ),
            });
        }

        let write_txn = self
            .cf
            .begin_write()
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to begin transaction: {}", e),
            })?;

        let mut vectors = VectorTable::<DIM>::open(&write_txn, &self.table_name).map_err(|e| {
            QueryError::ExecutionError {
                message: format!("Failed to open VectorTable: {}", e),
            }
        })?;

        // Convert to fixed-size array
        let mut arr = [0.0f32; DIM];
        arr.copy_from_slice(vector);

        vectors
            .insert(id, &arr)
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to insert vector: {}", e),
            })?;

        drop(vectors);
        write_txn.commit().map_err(|e| QueryError::ExecutionError {
            message: format!("Failed to commit transaction: {}", e),
        })?;

        Ok(())
    }

    /// Get a vector for an entity
    pub fn get(&self, id: &Uuid) -> Result<Option<Vec<f32>>> {
        let read_txn = self
            .cf
            .begin_read()
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to begin read transaction: {}", e),
            })?;

        let vectors = VectorTableRead::<DIM>::open(&read_txn, &self.table_name).map_err(|e| {
            QueryError::ExecutionError {
                message: format!("Failed to open VectorTable: {}", e),
            }
        })?;

        let result = vectors.get(id).map_err(|e| QueryError::ExecutionError {
            message: format!("Failed to read vector: {}", e),
        })?;

        Ok(result.map(|guard| guard.value().to_vec()))
    }

    /// Search for similar vectors using brute-force cosine similarity
    ///
    /// This implementation scans all vectors and computes cosine similarity.
    /// For production use with large datasets, consider integrating HNSW.
    ///
    /// # Arguments
    ///
    /// * `query` - Query vector to search for
    /// * `limit` - Maximum number of results to return
    ///
    /// # Returns
    ///
    /// Returns UUIDs sorted by similarity (highest first)
    pub fn search_similar(&self, query: &[f32], limit: usize) -> Result<Vec<Uuid>> {
        if query.len() != DIM {
            return Err(QueryError::ExecutionError {
                message: format!(
                    "Query vector dimension mismatch: expected {}, got {}",
                    DIM,
                    query.len()
                ),
            });
        }

        let read_txn = self
            .cf
            .begin_read()
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to begin read transaction: {}", e),
            })?;

        let vectors = VectorTableRead::<DIM>::open(&read_txn, &self.table_name).map_err(|e| {
            QueryError::ExecutionError {
                message: format!("Failed to open VectorTable: {}", e),
            }
        })?;

        // Compute cosine similarity for all vectors
        let mut similarities: Vec<(Uuid, f32)> = Vec::new();

        // Iterate over all vectors in the table
        // Note: This is a brute-force scan - O(n) where n is number of vectors
        let iter = vectors
            .all_vectors()
            .map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to iterate vectors: {}", e),
            })?;

        for result in iter {
            let (id, vector_guard) = result.map_err(|e| QueryError::ExecutionError {
                message: format!("Failed to read vector entry: {}", e),
            })?;

            let vector = vector_guard.value();
            let similarity = cosine_similarity(query, vector);
            similarities.push((id, similarity));
        }

        // Sort by similarity (descending)
        similarities.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

        // Take top K results
        let results: Vec<Uuid> = similarities
            .into_iter()
            .take(limit)
            .map(|(id, _)| id)
            .collect();

        Ok(results)
    }
}

/// Compute cosine similarity between two vectors
///
/// Returns a value between -1.0 and 1.0, where 1.0 means identical direction.
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
    debug_assert_eq!(a.len(), b.len(), "Vectors must have same length");

    let mut dot_product = 0.0;
    let mut norm_a = 0.0;
    let mut norm_b = 0.0;

    for i in 0..a.len() {
        dot_product += a[i] * b[i];
        norm_a += a[i] * a[i];
        norm_b += b[i] * b[i];
    }

    let magnitude = (norm_a * norm_b).sqrt();
    if magnitude == 0.0 {
        0.0
    } else {
        dot_product / magnitude
    }
}

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

    #[tokio::test]
    async fn test_database_open() {
        let temp_dir = std::env::temp_dir().join("audb_test_manifold_open.manifold");
        let wal_path = temp_dir.with_extension("wal");
        let _ = std::fs::remove_file(&temp_dir);
        let _ = std::fs::remove_file(&wal_path);

        let db = Database::open(&temp_dir).await;
        assert!(db.is_ok());

        let db = db.unwrap();
        assert_eq!(db.path(), temp_dir.as_path());

        // Cleanup
        let _ = std::fs::remove_file(&temp_dir);
        let _ = std::fs::remove_file(&wal_path);
    }

    #[tokio::test]
    async fn test_create_and_get_entity() {
        let temp_dir = std::env::temp_dir().join("audb_test_manifold_crud.manifold");
        let wal_path = temp_dir.with_extension("wal");
        let _ = std::fs::remove_file(&temp_dir);
        let _ = std::fs::remove_file(&wal_path);

        let db = Database::open(&temp_dir).await.unwrap();
        let collection = db.collection("users").unwrap();

        let id = Uuid::new_v4();
        let data = json!({
            "name": "Alice",
            "age": 42,
            "active": true
        });

        // Create entity
        collection.create_entity(id, data.clone()).unwrap();

        // Get entity
        let retrieved = collection.get_entity(id).unwrap();
        assert!(retrieved.is_some());

        let retrieved = retrieved.unwrap();
        assert_eq!(retrieved["name"], "Alice");
        assert_eq!(retrieved["age"], 42);
        assert_eq!(retrieved["active"], true);

        // Cleanup
        let _ = std::fs::remove_file(&temp_dir);
        let _ = std::fs::remove_file(&wal_path);
    }

    #[tokio::test]
    async fn test_update_entity() {
        let temp_dir = std::env::temp_dir().join("audb_test_manifold_update.manifold");
        let wal_path = temp_dir.with_extension("wal");
        let _ = std::fs::remove_file(&temp_dir);
        let _ = std::fs::remove_file(&wal_path);

        let db = Database::open(&temp_dir).await.unwrap();
        let collection = db.collection("users").unwrap();

        let id = Uuid::new_v4();
        let data = json!({ "name": "Alice", "age": 42 });

        collection.create_entity(id, data).unwrap();

        // Update
        let updated = json!({ "name": "Alice", "age": 43 });
        collection.update_entity(id, updated).unwrap();

        // Verify
        let retrieved = collection.get_entity(id).unwrap().unwrap();
        assert_eq!(retrieved["age"], 43);

        // Cleanup
        let _ = std::fs::remove_file(&temp_dir);
        let _ = std::fs::remove_file(&wal_path);
    }

    #[tokio::test]
    async fn test_delete_entity() {
        let temp_dir = std::env::temp_dir().join("audb_test_manifold_delete.manifold");
        let wal_path = temp_dir.with_extension("wal");
        let _ = std::fs::remove_file(&temp_dir);
        let _ = std::fs::remove_file(&wal_path);

        let db = Database::open(&temp_dir).await.unwrap();
        let collection = db.collection("users").unwrap();

        let id = Uuid::new_v4();
        let data = json!({ "name": "Bob" });

        collection.create_entity(id, data).unwrap();
        assert!(collection.get_entity(id).unwrap().is_some());

        collection.delete_entity(id).unwrap();
        assert!(collection.get_entity(id).unwrap().is_none());

        // Cleanup
        let _ = std::fs::remove_file(&temp_dir);
        let _ = std::fs::remove_file(&wal_path);
    }

    #[tokio::test]
    async fn test_edges() {
        let temp_dir = std::env::temp_dir().join("audb_test_manifold_edges.manifold");
        let wal_path = temp_dir.with_extension("wal");
        let _ = std::fs::remove_file(&temp_dir);
        let _ = std::fs::remove_file(&wal_path);

        let db = Database::open(&temp_dir).await.unwrap();
        let collection = db.collection("test").unwrap();

        let user = Uuid::new_v4();
        let post1 = Uuid::new_v4();
        let post2 = Uuid::new_v4();

        // Add edges
        collection.add_edge(post1, "authored_by", user).unwrap();
        collection.add_edge(post2, "authored_by", user).unwrap();

        // Get outgoing edges from posts
        let authors1 = collection.get_outgoing_edges(post1, "authored_by").unwrap();
        assert_eq!(authors1, vec![user]);

        // Get incoming edges to user
        let authored_posts = collection.get_incoming_edges(user, "authored_by").unwrap();
        assert_eq!(authored_posts.len(), 2);
        assert!(authored_posts.contains(&post1));
        assert!(authored_posts.contains(&post2));

        // Cleanup
        let _ = std::fs::remove_file(&temp_dir);
        let _ = std::fs::remove_file(&wal_path);
    }

    #[tokio::test]
    async fn test_vectors() {
        let temp_dir = std::env::temp_dir().join("audb_test_manifold_vectors.manifold");
        let wal_path = temp_dir.with_extension("wal");
        let _ = std::fs::remove_file(&temp_dir);
        let _ = std::fs::remove_file(&wal_path);

        let db = Database::open(&temp_dir).await.unwrap();
        let collection = db.collection("documents").unwrap();

        let id = Uuid::new_v4();
        let embedding = vec![0.1f32, 0.2, 0.3, 0.4]; // 4D vector for testing

        // Get vector table with dimension 4
        let vectors = collection.vectors::<4>("embeddings").unwrap();

        // Insert vector
        vectors.insert(&id, &embedding).unwrap();

        // Get vector
        let retrieved = vectors.get(&id).unwrap();
        assert!(retrieved.is_some());
        let retrieved_vec = retrieved.unwrap();
        assert_eq!(retrieved_vec.len(), 4);
        assert_eq!(retrieved_vec, embedding);

        // Test dimension mismatch error
        let wrong_dim = vec![0.1f32; 8];
        let result = vectors.insert(&id, &wrong_dim);
        assert!(result.is_err());

        // Cleanup
        let _ = std::fs::remove_file(&temp_dir);
        let _ = std::fs::remove_file(&wal_path);
    }

    #[tokio::test]
    async fn test_vector_similarity_search() {
        let temp_dir = std::env::temp_dir().join("audb_test_manifold_similarity.manifold");
        let wal_path = temp_dir.with_extension("wal");
        let _ = std::fs::remove_file(&temp_dir);
        let _ = std::fs::remove_file(&wal_path);

        let db = Database::open(&temp_dir).await.unwrap();
        let collection = db.collection("documents").unwrap();

        let vectors = collection.vectors::<4>("embeddings").unwrap();

        // Insert test vectors
        let id1 = Uuid::new_v4();
        let id2 = Uuid::new_v4();
        let id3 = Uuid::new_v4();

        // Similar to query
        let vec1 = vec![1.0f32, 0.0, 0.0, 0.0];
        // Somewhat similar
        let vec2 = vec![0.7f32, 0.7, 0.0, 0.0];
        // Different
        let vec3 = vec![0.0f32, 0.0, 1.0, 0.0];

        vectors.insert(&id1, &vec1).unwrap();
        vectors.insert(&id2, &vec2).unwrap();
        vectors.insert(&id3, &vec3).unwrap();

        // Search with query similar to vec1
        let query = vec![0.9f32, 0.1, 0.0, 0.0];
        let results = vectors.search_similar(&query, 2).unwrap();

        // Should return id1 first (most similar)
        assert_eq!(results.len(), 2);
        assert_eq!(results[0], id1);

        // Cleanup
        let _ = std::fs::remove_file(&temp_dir);
        let _ = std::fs::remove_file(&wal_path);
    }

    #[test]
    fn test_cosine_similarity() {
        // Identical vectors
        let a = vec![1.0f32, 0.0, 0.0];
        let b = vec![1.0f32, 0.0, 0.0];
        let sim = cosine_similarity(&a, &b);
        assert!((sim - 1.0).abs() < 0.001);

        // Orthogonal vectors
        let a = vec![1.0f32, 0.0, 0.0];
        let b = vec![0.0f32, 1.0, 0.0];
        let sim = cosine_similarity(&a, &b);
        assert!(sim.abs() < 0.001);

        // Opposite vectors
        let a = vec![1.0f32, 0.0, 0.0];
        let b = vec![-1.0f32, 0.0, 0.0];
        let sim = cosine_similarity(&a, &b);
        assert!((sim + 1.0).abs() < 0.001);

        // Similar vectors
        let a = vec![1.0f32, 0.5, 0.0];
        let b = vec![0.9f32, 0.4, 0.0];
        let sim = cosine_similarity(&a, &b);
        assert!(sim > 0.99); // Very similar
    }
}