manifoldb 0.1.4

A multi-paradigm embedded database for graph, vector, and relational data
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
//! Backup import (restore) functionality.
//!
//! This module provides functions to restore database contents from a
//! JSON-lines backup file.

use std::collections::HashSet;
use std::io::{BufRead, BufReader, Read};

use super::error::{BackupError, BackupResult};
use super::types::{
    BackupMetadata, BackupRecord, BackupRecordType, BackupStatistics, KeyValueRecord, RecordData,
    BACKUP_FORMAT_VERSION,
};
use crate::Database;

/// Well-known table names for restoration.
mod tables {
    pub const METADATA: &str = "metadata";
}

/// Options for controlling the import process.
#[derive(Debug, Clone)]
#[allow(clippy::struct_excessive_bools)]
pub struct ImportOptions {
    /// Whether to verify referential integrity (edges reference existing entities).
    pub verify_references: bool,

    /// Whether to skip duplicate records instead of failing.
    pub skip_duplicates: bool,

    /// Whether to rebuild indexes after import.
    pub rebuild_indexes: bool,

    /// Maximum number of records to import in a single transaction.
    /// Use None for unlimited (all in one transaction).
    pub batch_size: Option<usize>,

    /// Whether to perform a dry run (verify without writing).
    pub dry_run: bool,
}

impl Default for ImportOptions {
    fn default() -> Self {
        Self {
            verify_references: true,
            skip_duplicates: false,
            rebuild_indexes: true,
            batch_size: Some(10_000),
            dry_run: false,
        }
    }
}

impl ImportOptions {
    /// Create options for a fast import without verification.
    pub fn fast() -> Self {
        Self {
            verify_references: false,
            skip_duplicates: true,
            rebuild_indexes: false,
            batch_size: Some(50_000),
            dry_run: false,
        }
    }

    /// Create options for a dry run.
    pub fn dry_run() -> Self {
        Self { dry_run: true, ..Default::default() }
    }
}

/// An importer for restoring backup data.
///
/// This struct provides a streaming interface for reading and restoring
/// backup records, allowing large backups to be restored efficiently.
pub struct Importer<R: Read> {
    reader: BufReader<R>,
    metadata: Option<BackupMetadata>,
    options: ImportOptions,
    statistics: BackupStatistics,
    line_number: u64,
}

impl<R: Read> Importer<R> {
    /// Create a new importer with default options.
    pub fn new(reader: R) -> Self {
        Self::with_options(reader, ImportOptions::default())
    }

    /// Create a new importer with custom options.
    pub fn with_options(reader: R, options: ImportOptions) -> Self {
        Self {
            reader: BufReader::new(reader),
            metadata: None,
            options,
            statistics: BackupStatistics::default(),
            line_number: 0,
        }
    }

    /// Read and validate the backup metadata.
    ///
    /// This must be called before importing data.
    pub fn read_metadata(&mut self) -> BackupResult<&BackupMetadata> {
        if let Some(ref meta) = self.metadata {
            return Ok(meta);
        }

        let record =
            self.read_record()?.ok_or_else(|| BackupError::incomplete("empty backup file"))?;

        match record.record_type {
            BackupRecordType::Metadata => {
                if let RecordData::Metadata(meta) = record.data {
                    // Validate version
                    if meta.version > BACKUP_FORMAT_VERSION {
                        return Err(BackupError::UnsupportedVersion(meta.version));
                    }
                    Ok(self.metadata.insert(meta))
                } else {
                    Err(BackupError::malformed_record(
                        self.line_number,
                        "metadata record has wrong data type",
                    ))
                }
            }
            _ => Err(BackupError::malformed_record(
                self.line_number,
                "first record must be metadata",
            )),
        }
    }

    /// Get the backup metadata (after reading it).
    pub fn metadata(&self) -> Option<&BackupMetadata> {
        self.metadata.as_ref()
    }

    /// Get the current import statistics.
    pub fn statistics(&self) -> &BackupStatistics {
        &self.statistics
    }

    /// Read the next record from the backup.
    pub fn read_record(&mut self) -> BackupResult<Option<BackupRecord>> {
        let mut line = String::new();
        let bytes_read = self.reader.read_line(&mut line)?;

        if bytes_read == 0 {
            return Ok(None);
        }

        self.line_number += 1;
        let line = line.trim();

        if line.is_empty() {
            return self.read_record(); // Skip empty lines
        }

        let record: BackupRecord = serde_json::from_str(line).map_err(|e| {
            BackupError::Deserialization(format!("line {}: {}", self.line_number, e))
        })?;

        Ok(Some(record))
    }

    /// Import all records into the database.
    pub fn import_all(mut self, db: &Database) -> BackupResult<BackupStatistics> {
        // Read and validate metadata first
        self.read_metadata()?;

        if self.options.dry_run {
            return self.verify_all();
        }

        // Collect entity IDs for reference checking
        let mut entity_ids: HashSet<u64> = HashSet::new();

        // Process records in batches
        let batch_size = self.options.batch_size.unwrap_or(usize::MAX);
        let mut batch_records: Vec<BackupRecord> = Vec::with_capacity(batch_size.min(10_000));

        loop {
            // Read a batch of records
            batch_records.clear();

            for _ in 0..batch_size {
                match self.read_record()? {
                    Some(record) => {
                        if matches!(record.record_type, BackupRecordType::EndOfBackup) {
                            break;
                        }
                        batch_records.push(record);
                    }
                    None => break,
                }
            }

            if batch_records.is_empty() {
                break;
            }

            // Process this batch in a transaction
            let mut tx = db.begin()?;

            for record in &batch_records {
                match &record.record_type {
                    BackupRecordType::Entity => {
                        if let RecordData::Entity(entity_record) = &record.data {
                            entity_ids.insert(entity_record.id);
                            let entity = entity_record.to_entity();
                            tx.put_entity(&entity)?;
                            self.statistics.add_entity();
                        }
                    }
                    BackupRecordType::Edge => {
                        if let RecordData::Edge(edge_record) = &record.data {
                            // Verify references if enabled
                            if self.options.verify_references {
                                if !entity_ids.contains(&edge_record.source) {
                                    return Err(BackupError::MissingReference(format!(
                                        "edge {} references missing source entity {}",
                                        edge_record.id, edge_record.source
                                    )));
                                }
                                if !entity_ids.contains(&edge_record.target) {
                                    return Err(BackupError::MissingReference(format!(
                                        "edge {} references missing target entity {}",
                                        edge_record.id, edge_record.target
                                    )));
                                }
                            }

                            let edge = edge_record.to_edge();
                            tx.put_edge(&edge)?;
                            self.statistics.add_edge();
                        }
                    }
                    BackupRecordType::KeyValue => {
                        if let RecordData::KeyValue(kv) = &record.data {
                            if let Some(table) = &record.table {
                                self.import_key_value(&mut tx, table, kv)?;
                                self.statistics.add_metadata();
                            }
                        }
                    }
                    BackupRecordType::Metadata | BackupRecordType::EndOfBackup => {
                        // Already handled or marker
                    }
                }
            }

            tx.commit()?;
        }

        Ok(self.statistics)
    }

    /// Import a key-value record.
    fn import_key_value<T: manifoldb_storage::Transaction>(
        &self,
        tx: &mut crate::transaction::DatabaseTransaction<T>,
        table: &str,
        kv: &KeyValueRecord,
    ) -> BackupResult<()> {
        // Only import metadata table
        if table == tables::METADATA {
            tx.put_metadata(&kv.key, &kv.value)?;
        }
        Ok(())
    }

    /// Verify all records without importing (dry run).
    fn verify_all(mut self) -> BackupResult<BackupStatistics> {
        let mut entity_ids: HashSet<u64> = HashSet::new();

        while let Some(record) = self.read_record()? {
            match &record.record_type {
                BackupRecordType::Entity => {
                    if let RecordData::Entity(entity_record) = &record.data {
                        entity_ids.insert(entity_record.id);
                        self.statistics.add_entity();
                    }
                }
                BackupRecordType::Edge => {
                    if let RecordData::Edge(edge_record) = &record.data {
                        if self.options.verify_references {
                            if !entity_ids.contains(&edge_record.source) {
                                return Err(BackupError::MissingReference(format!(
                                    "edge {} references missing source entity {}",
                                    edge_record.id, edge_record.source
                                )));
                            }
                            if !entity_ids.contains(&edge_record.target) {
                                return Err(BackupError::MissingReference(format!(
                                    "edge {} references missing target entity {}",
                                    edge_record.id, edge_record.target
                                )));
                            }
                        }
                        self.statistics.add_edge();
                    }
                }
                BackupRecordType::KeyValue => {
                    self.statistics.add_metadata();
                }
                BackupRecordType::EndOfBackup => {
                    break;
                }
                BackupRecordType::Metadata => {
                    // Already processed
                }
            }
        }

        Ok(self.statistics)
    }
}

/// Import a backup into the database.
///
/// This is a convenience function that creates an importer and runs the import.
///
/// # Arguments
///
/// * `db` - The database to restore into
/// * `reader` - The input reader containing backup data
///
/// # Returns
///
/// Returns statistics about the import on success.
///
/// # Examples
///
/// ```ignore
/// use manifoldb::{Database, backup};
/// use std::fs::File;
/// use std::io::BufReader;
///
/// let db = Database::open("restored.manifold")?;
/// let file = File::open("backup.jsonl")?;
/// let reader = BufReader::new(file);
///
/// let stats = backup::import(&db, reader)?;
/// println!("Restored {} entities", stats.entity_count);
/// ```
pub fn import<R: Read>(db: &Database, reader: R) -> BackupResult<BackupStatistics> {
    let importer = Importer::new(reader);
    importer.import_all(db)
}

/// Verify a backup without importing.
///
/// This performs a dry run of the import process, validating the backup
/// format and checking referential integrity without modifying the database.
///
/// # Arguments
///
/// * `reader` - The input reader containing backup data
///
/// # Returns
///
/// Returns statistics about what would be imported on success.
pub fn verify<R: Read>(reader: R) -> BackupResult<BackupStatistics> {
    let importer = Importer::with_options(reader, ImportOptions::dry_run());
    importer.import_all(&Database::in_memory()?)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backup::export::export_full;
    use std::io::Cursor;

    #[test]
    fn test_import_options_default() {
        let opts = ImportOptions::default();
        assert!(opts.verify_references);
        assert!(!opts.skip_duplicates);
        assert!(opts.rebuild_indexes);
        assert!(!opts.dry_run);
    }

    #[test]
    fn test_import_options_fast() {
        let opts = ImportOptions::fast();
        assert!(!opts.verify_references);
        assert!(opts.skip_duplicates);
        assert!(!opts.rebuild_indexes);
    }

    #[test]
    fn test_roundtrip_empty_db() {
        let source_db = Database::in_memory().unwrap();

        // Export
        let mut buffer = Vec::new();
        let _stats = export_full(&source_db, &mut buffer).unwrap();

        // Import into new database
        let target_db = Database::in_memory().unwrap();
        let cursor = Cursor::new(buffer);
        let stats = import(&target_db, cursor).unwrap();

        assert_eq!(stats.entity_count, 0);
        assert_eq!(stats.edge_count, 0);
    }

    #[test]
    fn test_roundtrip_with_data() {
        let source_db = Database::in_memory().unwrap();

        // Add data to source
        {
            let mut tx = source_db.begin().unwrap();
            let e1 =
                tx.create_entity().unwrap().with_label("Person").with_property("name", "Alice");
            let e2 = tx.create_entity().unwrap().with_label("Person").with_property("name", "Bob");
            tx.put_entity(&e1).unwrap();
            tx.put_entity(&e2).unwrap();

            let edge =
                tx.create_edge(e1.id, e2.id, "KNOWS").unwrap().with_property("since", 2024i64);
            tx.put_edge(&edge).unwrap();
            tx.commit().unwrap();
        }

        // Export
        let mut buffer = Vec::new();
        let export_stats = export_full(&source_db, &mut buffer).unwrap();
        assert_eq!(export_stats.entity_count, 2);
        assert_eq!(export_stats.edge_count, 1);

        // Import into new database
        let target_db = Database::in_memory().unwrap();
        let cursor = Cursor::new(buffer);
        let import_stats = import(&target_db, cursor).unwrap();

        assert_eq!(import_stats.entity_count, 2);
        assert_eq!(import_stats.edge_count, 1);

        // Verify data was restored correctly
        let tx = target_db.begin_read().unwrap();
        let entities = tx.iter_entities(Some("Person")).unwrap();
        assert_eq!(entities.len(), 2);
    }

    #[test]
    fn test_verify_backup() {
        let db = Database::in_memory().unwrap();

        // Add data
        {
            let mut tx = db.begin().unwrap();
            let e1 = tx.create_entity().unwrap().with_label("Test");
            let e2 = tx.create_entity().unwrap().with_label("Test");
            tx.put_entity(&e1).unwrap();
            tx.put_entity(&e2).unwrap();

            let edge = tx.create_edge(e1.id, e2.id, "LINKS").unwrap();
            tx.put_edge(&edge).unwrap();
            tx.commit().unwrap();
        }

        // Export
        let mut buffer = Vec::new();
        export_full(&db, &mut buffer).unwrap();

        // Verify (dry run)
        let cursor = Cursor::new(buffer);
        let stats = verify(cursor).unwrap();

        assert_eq!(stats.entity_count, 2);
        assert_eq!(stats.edge_count, 1);
    }

    #[test]
    fn test_missing_reference_detection() {
        // Create a backup with an edge referencing non-existent entities
        let backup = r#"{"type":"metadata","data":{"version":1,"format":"json_lines","created_at":0,"sequence_number":0,"is_incremental":false,"previous_sequence":null,"statistics":{"entity_count":0,"edge_count":0,"metadata_count":0,"total_records":0,"uncompressed_size":0}}}
{"type":"edge","data":{"id":1,"source":999,"target":998,"edge_type":"BROKEN","properties":{}}}"#;

        let cursor = Cursor::new(backup.as_bytes());
        let result = verify(cursor);

        assert!(result.is_err());
        match result {
            Err(BackupError::MissingReference(_)) => (),
            _ => panic!("expected MissingReference error"),
        }
    }

    #[test]
    fn test_empty_backup_file() {
        let cursor = Cursor::new(b"");
        let result = verify(cursor);

        assert!(result.is_err());
        match result {
            Err(BackupError::Incomplete(msg)) => {
                assert!(msg.contains("empty"), "Expected 'empty' in message: {msg}");
            }
            other => panic!("expected Incomplete error, got: {other:?}"),
        }
    }

    #[test]
    fn test_truncated_json_line() {
        // Valid metadata followed by truncated JSON
        let backup = r#"{"type":"metadata","data":{"version":1,"format":"json_lines","created_at":0,"sequence_number":0,"is_incremental":false,"previous_sequence":null,"statistics":{"entity_count":0,"edge_count":0,"metadata_count":0,"total_records":0,"uncompressed_size":0}}}
{"type":"entity","data":{"id":1,"labels":["Test"],"properties":{"#;

        let cursor = Cursor::new(backup.as_bytes());
        let result = verify(cursor);

        assert!(result.is_err());
        match result {
            Err(BackupError::Deserialization(msg)) => {
                assert!(msg.contains("line 2"), "Expected line number in message: {msg}");
            }
            other => panic!("expected Deserialization error, got: {other:?}"),
        }
    }

    #[test]
    fn test_invalid_json_syntax() {
        // Invalid JSON on first line
        let backup = "not valid json at all";

        let cursor = Cursor::new(backup.as_bytes());
        let result = verify(cursor);

        assert!(result.is_err());
        match result {
            Err(BackupError::Deserialization(msg)) => {
                assert!(msg.contains("line 1"), "Expected line number in message: {msg}");
            }
            other => panic!("expected Deserialization error, got: {other:?}"),
        }
    }

    #[test]
    fn test_non_metadata_first_record() {
        // Entity record instead of metadata first
        let backup = r#"{"type":"entity","data":{"id":1,"labels":["Test"],"properties":{}}}"#;

        let cursor = Cursor::new(backup.as_bytes());
        let result = verify(cursor);

        assert!(result.is_err());
        match result {
            Err(BackupError::MalformedRecord { line, message }) => {
                assert_eq!(line, 1);
                assert!(
                    message.contains("first record must be metadata"),
                    "Unexpected message: {message}"
                );
            }
            other => panic!("expected MalformedRecord error, got: {other:?}"),
        }
    }

    #[test]
    fn test_unsupported_version() {
        // Future version that shouldn't be supported
        let backup = r#"{"type":"metadata","data":{"version":999,"format":"json_lines","created_at":0,"sequence_number":0,"is_incremental":false,"previous_sequence":null,"statistics":{"entity_count":0,"edge_count":0,"metadata_count":0,"total_records":0,"uncompressed_size":0}}}"#;

        let cursor = Cursor::new(backup.as_bytes());
        let result = verify(cursor);

        assert!(result.is_err());
        match result {
            Err(BackupError::UnsupportedVersion(version)) => {
                assert_eq!(version, 999);
            }
            other => panic!("expected UnsupportedVersion error, got: {other:?}"),
        }
    }

    #[test]
    fn test_corrupted_entity_record() {
        // Valid metadata but entity record with wrong data type
        let backup = r#"{"type":"metadata","data":{"version":1,"format":"json_lines","created_at":0,"sequence_number":0,"is_incremental":false,"previous_sequence":null,"statistics":{"entity_count":0,"edge_count":0,"metadata_count":0,"total_records":0,"uncompressed_size":0}}}
{"type":"entity","data":{"wrong_field":"bad_value"}}"#;

        let cursor = Cursor::new(backup.as_bytes());
        let result = verify(cursor);

        // This should fail during deserialization because the data doesn't match EntityRecord
        assert!(result.is_err());
    }
}