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().into()), 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
164#![cfg_attr(not(test), warn(missing_docs))]
165mod error;
166mod from_csv;
167mod to_csv;
168
169// Re-export public API
170pub use error::{CsvError, Result};
171pub use from_csv::{
172    from_csv,
173    from_csv_reader,
174    from_csv_reader_with_config,
175    from_csv_with_config,
176    FromCsvConfig,
177    DEFAULT_MAX_CELL_SIZE,
178    // Security limit constants
179    DEFAULT_MAX_COLUMNS,
180    DEFAULT_MAX_HEADER_SIZE,
181    DEFAULT_MAX_ROWS,
182    DEFAULT_MAX_TOTAL_SIZE,
183};
184pub use to_csv::{
185    to_csv, to_csv_list, to_csv_list_with_config, to_csv_list_writer,
186    to_csv_list_writer_with_config, to_csv_with_config, to_csv_writer, to_csv_writer_with_config,
187    ToCsvConfig,
188};
189
190#[cfg(test)]
191mod integration_tests {
192    use super::*;
193    use hedl_core::{Document, Item, MatrixList, Node, Value};
194    use hedl_test::expr_value;
195
196    /// Test round-trip conversion: HEDL → CSV → HEDL
197    #[test]
198    fn test_round_trip_conversion() {
199        // Create original document
200        let mut doc = Document::new((1, 0));
201        // Per SPEC.md: MatrixList.schema includes all column names with ID first
202        let mut list = MatrixList::new(
203            "Person",
204            vec![
205                "id".to_string(),
206                "name".to_string(),
207                "age".to_string(),
208                "score".to_string(),
209                "active".to_string(),
210            ],
211        );
212
213        // Per SPEC.md: Node.fields contains ALL values including ID (first column)
214        list.add_row(Node::new(
215            "Person",
216            "1",
217            vec![
218                Value::String("1".to_string().into()),
219                Value::String("Alice".to_string().into()),
220                Value::Int(30),
221                Value::Float(95.5),
222                Value::Bool(true),
223            ],
224        ));
225
226        list.add_row(Node::new(
227            "Person",
228            "2",
229            vec![
230                Value::String("2".to_string().into()),
231                Value::String("Bob".to_string().into()),
232                Value::Int(25),
233                Value::Float(87.3),
234                Value::Bool(false),
235            ],
236        ));
237
238        doc.root.insert("people".to_string(), Item::List(list));
239
240        // Convert to CSV
241        let csv = to_csv(&doc).unwrap();
242
243        // Convert back to HEDL
244        let doc2 = from_csv(&csv, "Person", &["name", "age", "score", "active"]).unwrap();
245
246        // Verify structure
247        let list2 = doc2.get("persons").unwrap().as_list().unwrap();
248        assert_eq!(list2.rows.len(), 2);
249
250        // Verify first row
251        let row1 = &list2.rows[0];
252        assert_eq!(&*row1.id, "1");
253        assert_eq!(row1.fields[0], Value::Int(1)); // ID field
254        assert_eq!(row1.fields[1], Value::String("Alice".to_string().into()));
255        assert_eq!(row1.fields[2], Value::Int(30));
256        assert_eq!(row1.fields[3], Value::Float(95.5));
257        assert_eq!(row1.fields[4], Value::Bool(true));
258
259        // Verify second row
260        let row2 = &list2.rows[1];
261        assert_eq!(&*row2.id, "2");
262        assert_eq!(row2.fields[0], Value::Int(2)); // ID field
263        assert_eq!(row2.fields[1], Value::String("Bob".to_string().into()));
264        assert_eq!(row2.fields[2], Value::Int(25));
265        assert_eq!(row2.fields[3], Value::Float(87.3));
266        assert_eq!(row2.fields[4], Value::Bool(false));
267    }
268
269    /// Test handling of null values
270    #[test]
271    fn test_null_values() {
272        let mut doc = Document::new((1, 0));
273        let mut list = MatrixList::new("Item", vec!["id".to_string(), "value".to_string()]);
274
275        list.add_row(Node::new(
276            "Item",
277            "1",
278            vec![Value::String("1".to_string().into()), Value::Null],
279        ));
280        doc.root.insert("items".to_string(), Item::List(list));
281
282        let csv = to_csv(&doc).unwrap();
283        let doc2 = from_csv(&csv, "Item", &["value"]).unwrap();
284
285        let list2 = doc2.get("items").unwrap().as_list().unwrap();
286        assert_eq!(list2.rows[0].fields[0], Value::Int(1)); // ID field
287        assert_eq!(list2.rows[0].fields[1], Value::Null);
288    }
289
290    /// Test handling of references
291    #[test]
292    fn test_references() {
293        let mut doc = Document::new((1, 0));
294        let mut list = MatrixList::new("Item", vec!["id".to_string(), "ref".to_string()]);
295
296        list.add_row(Node::new(
297            "Item",
298            "1",
299            vec![
300                Value::String("1".to_string().into()),
301                Value::Reference(hedl_core::Reference::local("user1")),
302            ],
303        ));
304
305        list.add_row(Node::new(
306            "Item",
307            "2",
308            vec![
309                Value::String("2".to_string().into()),
310                Value::Reference(hedl_core::Reference::qualified("User", "user2")),
311            ],
312        ));
313
314        doc.root.insert("items".to_string(), Item::List(list));
315
316        let csv = to_csv(&doc).unwrap();
317        let doc2 = from_csv(&csv, "Item", &["ref"]).unwrap();
318
319        let list2 = doc2.get("items").unwrap().as_list().unwrap();
320
321        // Check local reference
322        assert_eq!(list2.rows[0].fields[0], Value::Int(1)); // ID field
323        let ref1 = list2.rows[0].fields[1].as_reference().unwrap();
324        assert_eq!(&*ref1.id, "user1");
325        assert_eq!(ref1.type_name, None);
326
327        // Check qualified reference
328        assert_eq!(list2.rows[1].fields[0], Value::Int(2)); // ID field
329        let ref2 = list2.rows[1].fields[1].as_reference().unwrap();
330        assert_eq!(&*ref2.id, "user2");
331        assert_eq!(ref2.type_name.as_deref(), Some("User"));
332    }
333
334    /// Test handling of mixed types
335    #[test]
336    fn test_mixed_types() {
337        let csv_data = r"
338id,value
3391,42
3402,3.25
3413,true
3424,hello
3435,@ref1
3446,
345";
346
347        let doc = from_csv(csv_data, "Item", &["value"]).unwrap();
348        let list = doc.get("items").unwrap().as_list().unwrap();
349
350        assert_eq!(list.rows.len(), 6);
351        assert_eq!(list.rows[0].fields[0], Value::Int(1)); // ID field
352        assert_eq!(list.rows[0].fields[1], Value::Int(42));
353        assert_eq!(list.rows[1].fields[0], Value::Int(2)); // ID field
354        assert_eq!(list.rows[1].fields[1], Value::Float(3.25));
355        assert_eq!(list.rows[2].fields[0], Value::Int(3)); // ID field
356        assert_eq!(list.rows[2].fields[1], Value::Bool(true));
357        assert_eq!(list.rows[3].fields[0], Value::Int(4)); // ID field
358        assert_eq!(
359            list.rows[3].fields[1],
360            Value::String("hello".to_string().into())
361        );
362        assert_eq!(list.rows[4].fields[0], Value::Int(5)); // ID field
363        assert!(matches!(list.rows[4].fields[1], Value::Reference(_)));
364        assert_eq!(list.rows[5].fields[0], Value::Int(6)); // ID field
365        assert_eq!(list.rows[5].fields[1], Value::Null);
366    }
367
368    /// Test expressions
369    #[test]
370    fn test_expressions() {
371        let mut doc = Document::new((1, 0));
372        let mut list = MatrixList::new("Item", vec!["id".to_string(), "expr".to_string()]);
373
374        list.add_row(Node::new(
375            "Item",
376            "1",
377            vec![
378                Value::String("1".to_string().into()),
379                expr_value("add(x, y)"),
380            ],
381        ));
382
383        doc.root.insert("items".to_string(), Item::List(list));
384
385        let csv = to_csv(&doc).unwrap();
386        assert!(csv.contains("$(add(x, y))"));
387
388        let doc2 = from_csv(&csv, "Item", &["expr"]).unwrap();
389        let list2 = doc2.get("items").unwrap().as_list().unwrap();
390
391        assert_eq!(list2.rows[0].fields[0], Value::Int(1)); // ID field
392        assert_eq!(list2.rows[0].fields[1], expr_value("add(x, y)"));
393    }
394}