hedl_csv/
lib.rs

1// Dweve HEDL - Hierarchical Entity Data Language
2//
3// Copyright (c) 2025 Dweve IP B.V. and individual contributors.
4//
5// SPDX-License-Identifier: Apache-2.0
6//
7// Licensed under the Apache License, Version 2.0 (the "License");
8// you may not use this file except in compliance with the License.
9// You may obtain a copy of the License in the LICENSE file at the
10// root of this repository or at: http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! CSV file ↔ HEDL format bidirectional conversion.
19//!
20//! This crate provides functionality to convert between CSV files and HEDL documents.
21//! It handles both reading CSV data into HEDL structures and writing HEDL data to CSV format.
22//!
23//! # Features
24//!
25//! - **Bidirectional conversion**: Convert HEDL → CSV and CSV → HEDL
26//! - **Type inference**: Automatically infer types when reading CSV (null, bool, int, float, string, references)
27//! - **Configurable**: Support for custom delimiters, quote styles, and header options
28//! - **Matrix lists**: CSV tables map naturally to HEDL matrix lists
29//! - **Error handling**: Comprehensive error reporting with context
30//!
31//! # Examples
32//!
33//! ## Converting HEDL to CSV
34//!
35//! ```no_run
36//! use hedl_core::{Document, Item, MatrixList, Node, Value};
37//! use hedl_csv::to_csv;
38//!
39//! let mut doc = Document::new((1, 0));
40//! let mut list = MatrixList::new("Person", vec!["name".to_string(), "age".to_string()]);
41//!
42//! list.add_row(Node::new(
43//!     "Person",
44//!     "1",
45//!     vec![Value::String("Alice".to_string()), Value::Int(30)],
46//! ));
47//!
48//! doc.root.insert("people".to_string(), Item::List(list));
49//!
50//! let csv_string = to_csv(&doc).unwrap();
51//! println!("{}", csv_string);
52//! // Output:
53//! // id,name,age
54//! // 1,Alice,30
55//! ```
56//!
57//! ## Converting CSV to HEDL
58//!
59//! ```no_run
60//! use hedl_csv::from_csv;
61//!
62//! let csv_data = r#"
63//! id,name,age,active
64//! 1,Alice,30,true
65//! 2,Bob,25,false
66//! "#;
67//!
68//! let doc = from_csv(csv_data, "Person", &["name", "age", "active"]).unwrap();
69//!
70//! // Access the matrix list
71//! let item = doc.get("persons").unwrap();
72//! let list = item.as_list().unwrap();
73//! assert_eq!(list.rows.len(), 2);
74//! ```
75//!
76//! ## Custom Configuration
77//!
78//! ```no_run
79//! use hedl_csv::{from_csv_with_config, to_csv_with_config, FromCsvConfig, ToCsvConfig};
80//!
81//! // Reading CSV with custom delimiter
82//! let csv_data = "id\tname\tage\n1\tAlice\t30";
83//! let config = FromCsvConfig {
84//!     delimiter: b'\t',
85//!     has_headers: true,
86//!     trim: true,
87//!     ..Default::default()
88//! };
89//! let doc = from_csv_with_config(csv_data, "Person", &["name", "age"], config).unwrap();
90//!
91//! // Writing CSV without headers
92//! let config = ToCsvConfig {
93//!     include_headers: false,
94//!     ..Default::default()
95//! };
96//! let csv_string = to_csv_with_config(&doc, config).unwrap();
97//! ```
98//!
99//! ## Custom List Keys (Irregular Plurals)
100//!
101//! ```no_run
102//! use hedl_csv::{from_csv_with_config, FromCsvConfig};
103//!
104//! let csv_data = "id,name,age\n1,Alice,30\n2,Bob,25";
105//!
106//! // Use "people" instead of default "persons" for Person type
107//! let config = FromCsvConfig {
108//!     list_key: Some("people".to_string()),
109//!     ..Default::default()
110//! };
111//! let doc = from_csv_with_config(csv_data, "Person", &["name", "age"], config).unwrap();
112//!
113//! // Access using the custom plural form
114//! let list = doc.get("people").unwrap().as_list().unwrap();
115//! assert_eq!(list.rows.len(), 2);
116//! ```
117//!
118//! ## Selective List Export
119//!
120//! When a document contains multiple lists, you can export each one independently
121//! without converting the entire document:
122//!
123//! ```no_run
124//! use hedl_core::Document;
125//! use hedl_csv::to_csv_list;
126//!
127//! let doc = Document::new((1, 0));
128//! // Export only the "people" list
129//! let csv_people = to_csv_list(&doc, "people").unwrap();
130//! // Export only the "items" list
131//! let csv_items = to_csv_list(&doc, "items").unwrap();
132//! ```
133//!
134//! This is useful when you want to export specific tables from multi-list documents
135//! without exporting everything.
136//!
137//! ## Round-trip Conversion
138//!
139//! ```no_run
140//! use hedl_csv::{from_csv, to_csv};
141//!
142//! let original_csv = "id,name,age\n1,Alice,30\n2,Bob,25\n";
143//! let doc = from_csv(original_csv, "Person", &["name", "age"]).unwrap();
144//! let converted_csv = to_csv(&doc).unwrap();
145//!
146//! // The structure is preserved
147//! assert_eq!(original_csv, converted_csv);
148//! ```
149//!
150//! # Type Inference
151//!
152//! When reading CSV data, values are automatically inferred as:
153//!
154//! - Empty string or `~` → `Value::Null`
155//! - `true` or `false` → `Value::Bool`
156//! - Integer pattern → `Value::Int`
157//! - Float pattern → `Value::Float`
158//! - `@id` or `@Type:id` → `Value::Reference`
159//! - `$(expr)` → `Value::Expression`
160//! - Otherwise → `Value::String`
161//!
162//! Special float values are supported: `NaN`, `Infinity`, `-Infinity`
163
164mod error;
165mod from_csv;
166mod to_csv;
167
168// Re-export public API
169pub use error::{CsvError, Result};
170pub use from_csv::{
171    from_csv, from_csv_reader, from_csv_reader_with_config, from_csv_with_config, FromCsvConfig,
172};
173pub use to_csv::{
174    to_csv, to_csv_list, to_csv_list_with_config, to_csv_list_writer, to_csv_list_writer_with_config,
175    to_csv_with_config, to_csv_writer, to_csv_writer_with_config, ToCsvConfig,
176};
177
178#[cfg(test)]
179mod integration_tests {
180    use super::*;
181    use hedl_core::{Document, Item, MatrixList, Node, Value};
182    use hedl_test::expr_value;
183
184    /// Test round-trip conversion: HEDL → CSV → HEDL
185    #[test]
186    fn test_round_trip_conversion() {
187        // Create original document
188        let mut doc = Document::new((1, 0));
189        // Per SPEC.md: MatrixList.schema includes all column names with ID first
190        let mut list = MatrixList::new(
191            "Person",
192            vec![
193                "id".to_string(),
194                "name".to_string(),
195                "age".to_string(),
196                "score".to_string(),
197                "active".to_string(),
198            ],
199        );
200
201        // Per SPEC.md: Node.fields contains ALL values including ID (first column)
202        list.add_row(Node::new(
203            "Person",
204            "1",
205            vec![
206                Value::String("1".to_string()),
207                Value::String("Alice".to_string()),
208                Value::Int(30),
209                Value::Float(95.5),
210                Value::Bool(true),
211            ],
212        ));
213
214        list.add_row(Node::new(
215            "Person",
216            "2",
217            vec![
218                Value::String("2".to_string()),
219                Value::String("Bob".to_string()),
220                Value::Int(25),
221                Value::Float(87.3),
222                Value::Bool(false),
223            ],
224        ));
225
226        doc.root.insert("people".to_string(), Item::List(list));
227
228        // Convert to CSV
229        let csv = to_csv(&doc).unwrap();
230
231        // Convert back to HEDL
232        let doc2 = from_csv(&csv, "Person", &["name", "age", "score", "active"]).unwrap();
233
234        // Verify structure
235        let list2 = doc2.get("persons").unwrap().as_list().unwrap();
236        assert_eq!(list2.rows.len(), 2);
237
238        // Verify first row
239        let row1 = &list2.rows[0];
240        assert_eq!(row1.id, "1");
241        assert_eq!(row1.fields[0], Value::Int(1)); // ID field
242        assert_eq!(row1.fields[1], Value::String("Alice".to_string()));
243        assert_eq!(row1.fields[2], Value::Int(30));
244        assert_eq!(row1.fields[3], Value::Float(95.5));
245        assert_eq!(row1.fields[4], Value::Bool(true));
246
247        // Verify second row
248        let row2 = &list2.rows[1];
249        assert_eq!(row2.id, "2");
250        assert_eq!(row2.fields[0], Value::Int(2)); // ID field
251        assert_eq!(row2.fields[1], Value::String("Bob".to_string()));
252        assert_eq!(row2.fields[2], Value::Int(25));
253        assert_eq!(row2.fields[3], Value::Float(87.3));
254        assert_eq!(row2.fields[4], Value::Bool(false));
255    }
256
257    /// Test handling of null values
258    #[test]
259    fn test_null_values() {
260        let mut doc = Document::new((1, 0));
261        let mut list = MatrixList::new("Item", vec!["id".to_string(), "value".to_string()]);
262
263        list.add_row(Node::new(
264            "Item",
265            "1",
266            vec![Value::String("1".to_string()), Value::Null],
267        ));
268        doc.root.insert("items".to_string(), Item::List(list));
269
270        let csv = to_csv(&doc).unwrap();
271        let doc2 = from_csv(&csv, "Item", &["value"]).unwrap();
272
273        let list2 = doc2.get("items").unwrap().as_list().unwrap();
274        assert_eq!(list2.rows[0].fields[0], Value::Int(1)); // ID field
275        assert_eq!(list2.rows[0].fields[1], Value::Null);
276    }
277
278    /// Test handling of references
279    #[test]
280    fn test_references() {
281        let mut doc = Document::new((1, 0));
282        let mut list = MatrixList::new("Item", vec!["id".to_string(), "ref".to_string()]);
283
284        list.add_row(Node::new(
285            "Item",
286            "1",
287            vec![
288                Value::String("1".to_string()),
289                Value::Reference(hedl_core::Reference::local("user1")),
290            ],
291        ));
292
293        list.add_row(Node::new(
294            "Item",
295            "2",
296            vec![
297                Value::String("2".to_string()),
298                Value::Reference(hedl_core::Reference::qualified("User", "user2")),
299            ],
300        ));
301
302        doc.root.insert("items".to_string(), Item::List(list));
303
304        let csv = to_csv(&doc).unwrap();
305        let doc2 = from_csv(&csv, "Item", &["ref"]).unwrap();
306
307        let list2 = doc2.get("items").unwrap().as_list().unwrap();
308
309        // Check local reference
310        assert_eq!(list2.rows[0].fields[0], Value::Int(1)); // ID field
311        let ref1 = list2.rows[0].fields[1].as_reference().unwrap();
312        assert_eq!(ref1.id, "user1");
313        assert_eq!(ref1.type_name, None);
314
315        // Check qualified reference
316        assert_eq!(list2.rows[1].fields[0], Value::Int(2)); // ID field
317        let ref2 = list2.rows[1].fields[1].as_reference().unwrap();
318        assert_eq!(ref2.id, "user2");
319        assert_eq!(ref2.type_name, Some("User".to_string()));
320    }
321
322    /// Test handling of mixed types
323    #[test]
324    fn test_mixed_types() {
325        let csv_data = r#"
326id,value
3271,42
3282,3.25
3293,true
3304,hello
3315,@ref1
3326,
333"#;
334
335        let doc = from_csv(csv_data, "Item", &["value"]).unwrap();
336        let list = doc.get("items").unwrap().as_list().unwrap();
337
338        assert_eq!(list.rows.len(), 6);
339        assert_eq!(list.rows[0].fields[0], Value::Int(1)); // ID field
340        assert_eq!(list.rows[0].fields[1], Value::Int(42));
341        assert_eq!(list.rows[1].fields[0], Value::Int(2)); // ID field
342        assert_eq!(list.rows[1].fields[1], Value::Float(3.25));
343        assert_eq!(list.rows[2].fields[0], Value::Int(3)); // ID field
344        assert_eq!(list.rows[2].fields[1], Value::Bool(true));
345        assert_eq!(list.rows[3].fields[0], Value::Int(4)); // ID field
346        assert_eq!(list.rows[3].fields[1], Value::String("hello".to_string()));
347        assert_eq!(list.rows[4].fields[0], Value::Int(5)); // ID field
348        assert!(matches!(list.rows[4].fields[1], Value::Reference(_)));
349        assert_eq!(list.rows[5].fields[0], Value::Int(6)); // ID field
350        assert_eq!(list.rows[5].fields[1], Value::Null);
351    }
352
353    /// Test expressions
354    #[test]
355    fn test_expressions() {
356        let mut doc = Document::new((1, 0));
357        let mut list = MatrixList::new("Item", vec!["id".to_string(), "expr".to_string()]);
358
359        list.add_row(Node::new(
360            "Item",
361            "1",
362            vec![Value::String("1".to_string()), expr_value("add(x, y)")],
363        ));
364
365        doc.root.insert("items".to_string(), Item::List(list));
366
367        let csv = to_csv(&doc).unwrap();
368        assert!(csv.contains("$(add(x, y))"));
369
370        let doc2 = from_csv(&csv, "Item", &["expr"]).unwrap();
371        let list2 = doc2.get("items").unwrap().as_list().unwrap();
372
373        assert_eq!(list2.rows[0].fields[0], Value::Int(1)); // ID field
374        assert_eq!(list2.rows[0].fields[1], expr_value("add(x, y)"));
375    }
376}