Skip to main content

dbx_core/engine/
snapshot.rs

1//! Database snapshot for save/load functionality
2//!
3//! Provides serialization/deserialization of entire database state
4
5use crate::engine::metadata::SchemaMetadata;
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8
9/// Complete database snapshot for serialization
10#[derive(Serialize, Deserialize, Debug, Clone)]
11pub struct DatabaseSnapshot {
12    /// Version for future compatibility
13    pub version: u32,
14
15    /// Table schemas
16    pub schemas: HashMap<String, SchemaMetadata>,
17
18    /// Index registry: index_name → (table, column)
19    pub indexes: HashMap<String, (String, String)>,
20
21    /// All table data
22    pub tables: HashMap<String, TableData>,
23
24    /// Row counters: table_name → next_row_id
25    pub row_counters: HashMap<String, usize>,
26}
27
28/// Data for a single table
29#[derive(Serialize, Deserialize, Debug, Clone)]
30pub struct TableData {
31    /// All key-value pairs in the table
32    pub entries: Vec<(Vec<u8>, Vec<u8>)>,
33}
34
35impl DatabaseSnapshot {
36    pub const CURRENT_VERSION: u32 = 1;
37
38    /// Create a new empty snapshot
39    pub fn new() -> Self {
40        Self {
41            version: Self::CURRENT_VERSION,
42            schemas: HashMap::new(),
43            indexes: HashMap::new(),
44            tables: HashMap::new(),
45            row_counters: HashMap::new(),
46        }
47    }
48}
49
50impl Default for DatabaseSnapshot {
51    fn default() -> Self {
52        Self::new()
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn test_snapshot_serialization() {
62        let mut snapshot = DatabaseSnapshot::new();
63        snapshot.row_counters.insert("users".to_string(), 42);
64
65        // Serialize to JSON
66        let json = serde_json::to_string(&snapshot).unwrap();
67        assert!(json.contains("\"version\":1"));
68
69        // Deserialize back
70        let restored: DatabaseSnapshot = serde_json::from_str(&json).unwrap();
71        assert_eq!(restored.version, DatabaseSnapshot::CURRENT_VERSION);
72        assert_eq!(restored.row_counters.get("users"), Some(&42));
73    }
74
75    #[test]
76    fn test_table_data_serialization() {
77        let table_data = TableData {
78            entries: vec![
79                (b"key1".to_vec(), b"value1".to_vec()),
80                (b"key2".to_vec(), b"value2".to_vec()),
81            ],
82        };
83
84        let json = serde_json::to_string(&table_data).unwrap();
85        let restored: TableData = serde_json::from_str(&json).unwrap();
86
87        assert_eq!(restored.entries.len(), 2);
88        assert_eq!(restored.entries[0].0, b"key1");
89        assert_eq!(restored.entries[0].1, b"value1");
90    }
91}