Skip to main content

hippmem_engine/
dump_api.rs

1//! Engine::dump — full JSONL export API.
2
3use crate::{DumpInput, DumpOutput, EngineResult};
4use std::io::Write;
5
6impl crate::Engine {
7    /// Exports all MemoryUnit entries as JSON Lines format.
8    ///
9    /// If `output_path` is Some, writes to a file and returns the path echo;
10    /// if None, returns the JSONL string.
11    pub fn dump(&self, input: DumpInput) -> EngineResult<DumpOutput> {
12        let units = crate::retrieve_api::load_all_units(self.store.db_arc());
13
14        // Build JSONL string
15        let mut buf = String::new();
16        for unit in &units {
17            let line = serde_json::to_string(unit).map_err(|e| {
18                crate::EngineError::Internal(format!("failed to serialize MemoryUnit: {}", e))
19            })?;
20            buf.push_str(&line);
21            buf.push('\n');
22        }
23
24        let count = units.len() as u64;
25
26        if let Some(path) = input.output_path {
27            // Write to file
28            let mut file = std::fs::File::create(&path).map_err(|e| {
29                crate::EngineError::Store(format!(
30                    "cannot create export file {}: {}",
31                    path.display(),
32                    e
33                ))
34            })?;
35            file.write_all(buf.as_bytes()).map_err(|e| {
36                crate::EngineError::Store(format!("failed to write export file: {}", e))
37            })?;
38
39            Ok(DumpOutput {
40                count,
41                written_to: Some(path),
42                json: None,
43            })
44        } else {
45            Ok(DumpOutput {
46                count,
47                written_to: None,
48                json: Some(buf),
49            })
50        }
51    }
52}