veloxx 0.4.0

Veloxx: High-performance, lightweight Rust library for in-memory data processing and analytics. Features DataFrames, Series, advanced I/O (CSV, JSON, Parquet), machine learning (linear regression, K-means, logistic regression), time-series analysis, data visualization, parallel processing, and multi-platform bindings (Python, WebAssembly). Designed for minimal dependencies, optimal memory usage, and blazing speed - ideal for data science, analytics, and performance-critical applications.
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
//! Advanced I/O Operations module for Velox.
//!
//! This module provides advanced data input/output capabilities including:
//! - Parquet file format support for columnar data
//! - Streaming JSON processing for large datasets
//! - Database connectivity (SQLite, PostgreSQL, MySQL)
//! - Asynchronous I/O operations
//!
//! # Features
//!
//! - High-performance Parquet reading and writing
//! - Memory-efficient streaming for large files
//! - Database integration with connection pooling
//! - Async/await support for non-blocking operations
//!
//! # Examples
//!
//! ```rust,no_run
//! use veloxx::dataframe::DataFrame;
//! use veloxx::series::Series;
//! use indexmap::IndexMap;
//!
//! # #[cfg(feature = "advanced_io")]
//! # {
//! use veloxx::advanced_io::{ParquetReader, ParquetWriter, DatabaseConnector};
//!
//! let mut columns = IndexMap::new();
//! columns.insert(
//!     "id".to_string(),
//!     Series::new_i32("id", vec![Some(1), Some(2), Some(3)]),
//! );
//! columns.insert(
//!     "name".to_string(),
//!     Series::new_string("name", vec![Some("Alice".to_string()), Some("Bob".to_string()), Some("Charlie".to_string())]),
//! );
//!
//! let df = DataFrame::new(columns).unwrap();
//!
//! // Write to Parquet
//! // let writer = ParquetWriter::new();
//! // writer.write_dataframe(&df, "data.parquet").await.unwrap();
//!
//! // Read from Parquet
//! // let reader = ParquetReader::new();
//! // let loaded_df = reader.read_dataframe("data.parquet").await.unwrap();
//! # }
//! ```

use crate::dataframe::DataFrame;
use crate::series::Series;
use crate::types::DataType;
use crate::VeloxxError;

use std::path::Path;

// use parquet::file::reader::{FileReader, SerializedFileReader}; // Removed unused import

/// Parquet file reader for high-performance columnar data access
pub struct ParquetReader {
    #[cfg(not(feature = "advanced_io"))]
    _phantom: std::marker::PhantomData<()>,
}

impl ParquetReader {
    /// Create a new Parquet reader
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use veloxx::advanced_io::ParquetReader;
    ///
    /// let reader = ParquetReader::new();
    /// ```
    pub fn new() -> Self {
        Self {
            #[cfg(not(feature = "advanced_io"))]
            _phantom: std::marker::PhantomData,
        }
    }

    /// Read a DataFrame from a Parquet file
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the Parquet file
    ///
    /// # Returns
    ///
    /// DataFrame containing the data from the Parquet file
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use veloxx::advanced_io::ParquetReader;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let reader = ParquetReader::new();
    /// // let df = reader.read_dataframe("data.parquet").await?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "advanced_io")]
    pub async fn read_dataframe<P: AsRef<Path>>(&self, path: P) -> Result<DataFrame, VeloxxError> {
        let path_buf = path.as_ref().to_path_buf();
        let path_str = path_buf.to_string_lossy().to_string();

        // Use spawn_blocking to run the synchronous parquet reader
        tokio::task::spawn_blocking(move || crate::io::arrow::read_parquet_to_dataframe(&path_str))
            .await
            .map_err(|e| VeloxxError::InvalidOperation(format!("Task join error: {}", e)))?
    }

    #[cfg(not(feature = "advanced_io"))]
    pub async fn read_dataframe<P: AsRef<Path>>(&self, _path: P) -> Result<DataFrame, VeloxxError> {
        Err(VeloxxError::InvalidOperation(
            "Advanced I/O feature is not enabled. Enable with --features advanced_io".to_string(),
        ))
    }

    /// Read a DataFrame from a Parquet file with streaming for large files
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the Parquet file
    /// * `batch_size` - Number of rows to read at a time
    ///
    /// # Returns
    ///
    /// Stream of DataFrames containing batches of data
    #[cfg(feature = "advanced_io")]
    pub async fn read_dataframe_streaming<P: AsRef<Path>>(
        &self,
        path: P,
        _batch_size: usize,
    ) -> Result<Vec<DataFrame>, VeloxxError> {
        // Placeholder for streaming implementation
        let df = self.read_dataframe(path).await?;
        Ok(vec![df])
    }

    #[cfg(not(feature = "advanced_io"))]
    pub async fn read_dataframe_streaming<P: AsRef<Path>>(
        &self,
        _path: P,
        _batch_size: usize,
    ) -> Result<Vec<DataFrame>, VeloxxError> {
        Err(VeloxxError::InvalidOperation(
            "Advanced I/O feature is not enabled. Enable with --features advanced_io".to_string(),
        ))
    }
}

impl Default for ParquetReader {
    fn default() -> Self {
        Self::new()
    }
}

/// Parquet file writer for high-performance columnar data storage
pub struct ParquetWriter {
    #[cfg(not(feature = "advanced_io"))]
    _phantom: std::marker::PhantomData<()>,
}

impl ParquetWriter {
    /// Create a new Parquet writer
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use veloxx::advanced_io::ParquetWriter;
    ///
    /// let writer = ParquetWriter::new();
    /// ```
    pub fn new() -> Self {
        Self {
            #[cfg(not(feature = "advanced_io"))]
            _phantom: std::marker::PhantomData,
        }
    }

    /// Write a DataFrame to a Parquet file
    ///
    /// # Arguments
    ///
    /// * `dataframe` - DataFrame to write
    /// * `path` - Path where the Parquet file should be created
    ///
    /// # Examples
    ///
    /// ```rust
    /// use veloxx::dataframe::DataFrame;
    /// use veloxx::series::Series;
    /// use veloxx::advanced_io::ParquetWriter;
    /// use indexmap::IndexMap;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut columns = IndexMap::new();
    /// columns.insert(
    ///     "id".to_string(),
    ///     Series::new_i32("id", vec![Some(1), Some(2)]),
    /// );
    ///
    /// let df = DataFrame::new(columns).unwrap();
    /// let writer = ParquetWriter::new();
    /// // writer.write_dataframe(&df, "output.parquet").await?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "advanced_io")]
    pub async fn write_dataframe<P: AsRef<Path>>(
        &self,
        dataframe: &DataFrame,
        path: P,
    ) -> Result<(), VeloxxError> {
        let path_buf = path.as_ref().to_path_buf();
        let path_str = path_buf.to_string_lossy().to_string();
        let df_clone = dataframe.clone();

        tokio::task::spawn_blocking(move || {
            crate::io::arrow::write_parquet_from_dataframe(&df_clone, &path_str)
        })
        .await
        .map_err(|e| VeloxxError::InvalidOperation(format!("Task join error: {}", e)))?
    }

    #[cfg(not(feature = "advanced_io"))]
    pub async fn write_dataframe<P: AsRef<Path>>(
        &self,
        _dataframe: &DataFrame,
        _path: P,
    ) -> Result<(), VeloxxError> {
        Err(VeloxxError::InvalidOperation(
            "Advanced I/O feature is not enabled. Enable with --features advanced_io".to_string(),
        ))
    }

    /// Write a DataFrame to a Parquet file with compression
    ///
    /// # Arguments
    ///
    /// * `dataframe` - DataFrame to write
    /// * `path` - Path where the Parquet file should be created
    /// * `compression` - Compression algorithm to use
    #[cfg(feature = "advanced_io")]
    pub async fn write_dataframe_compressed<P: AsRef<Path>>(
        &self,
        dataframe: &DataFrame,
        path: P,
        _compression: CompressionType,
    ) -> Result<(), VeloxxError> {
        // For now, delegate to regular write
        self.write_dataframe(dataframe, path).await
    }

    #[cfg(not(feature = "advanced_io"))]
    pub async fn write_dataframe_compressed<P: AsRef<Path>>(
        &self,
        _dataframe: &DataFrame,
        _path: P,
        _compression: CompressionType,
    ) -> Result<(), VeloxxError> {
        Err(VeloxxError::InvalidOperation(
            "Advanced I/O feature is not enabled. Enable with --features advanced_io".to_string(),
        ))
    }
}

impl Default for ParquetWriter {
    fn default() -> Self {
        Self::new()
    }
}

/// Compression types for Parquet files
#[derive(Debug, Clone, Copy)]
pub enum CompressionType {
    None,
    Snappy,
    Gzip,
    Lzo,
    Brotli,
    Lz4,
    Zstd,
}

/// JSON streaming processor for handling large JSON datasets
pub struct JsonStreamer {
    #[cfg(not(feature = "advanced_io"))]
    _phantom: std::marker::PhantomData<()>,
}

impl JsonStreamer {
    /// Create a new JSON streamer
    ///
    /// # Examples
    ///
    /// ```rust
    /// use veloxx::advanced_io::JsonStreamer;
    ///
    /// let streamer = JsonStreamer::new();
    /// ```
    pub fn new() -> Self {
        Self {
            #[cfg(not(feature = "advanced_io"))]
            _phantom: std::marker::PhantomData,
        }
    }

    /// Stream JSON data from a file and convert to DataFrames
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the JSON file
    /// * `batch_size` - Number of JSON objects to process per batch
    ///
    /// # Returns
    ///
    /// Stream of DataFrames containing batches of data
    #[cfg(feature = "advanced_io")]
    pub async fn stream_from_file<P: AsRef<Path>>(
        &self,
        path: P,
        batch_size: usize,
    ) -> Result<Vec<DataFrame>, VeloxxError> {
        let content = tokio::fs::read_to_string(path).await.map_err(|e| {
            VeloxxError::InvalidOperation(format!("Failed to read JSON file: {}", e))
        })?;

        self.stream_from_string(&content, batch_size).await
    }

    #[cfg(not(feature = "advanced_io"))]
    pub async fn stream_from_file<P: AsRef<Path>>(
        &self,
        _path: P,
        _batch_size: usize,
    ) -> Result<Vec<DataFrame>, VeloxxError> {
        Err(VeloxxError::InvalidOperation(
            "Advanced I/O feature is not enabled. Enable with --features advanced_io".to_string(),
        ))
    }

    /// Stream JSON data from a string and convert to DataFrames
    ///
    /// # Arguments
    ///
    /// * `json_str` - JSON string containing array of objects
    /// * `batch_size` - Number of JSON objects to process per batch
    ///
    /// # Returns
    ///
    /// Stream of DataFrames containing batches of data
    #[cfg(feature = "advanced_io")]
    pub async fn stream_from_string(
        &self,
        json_str: &str,
        _batch_size: usize,
    ) -> Result<Vec<DataFrame>, VeloxxError> {
        // Placeholder implementation - in reality would parse JSON incrementally
        let mut columns = indexmap::IndexMap::new();
        columns.insert(
            "json_data".to_string(),
            Series::new_string("json_data", vec![Some(json_str.to_string())]),
        );

        let df = DataFrame::new(columns);
        Ok(vec![df])
    }

    #[cfg(not(feature = "advanced_io"))]
    pub async fn stream_from_string(
        &self,
        _json_str: &str,
        _batch_size: usize,
    ) -> Result<Vec<DataFrame>, VeloxxError> {
        Err(VeloxxError::InvalidOperation(
            "Advanced I/O feature is not enabled. Enable with --features advanced_io".to_string(),
        ))
    }
}

impl Default for JsonStreamer {
    fn default() -> Self {
        Self::new()
    }
}

/// Database connector for various database systems
pub struct DatabaseConnector {
    #[cfg(feature = "advanced_io")]
    connection_string: String,
    #[cfg(not(feature = "advanced_io"))]
    _phantom: std::marker::PhantomData<()>,
}

impl DatabaseConnector {
    /// Create a new database connector
    ///
    /// # Arguments
    ///
    /// * `connection_string` - Database connection string
    ///
    /// # Examples
    ///
    /// ```rust
    /// use veloxx::advanced_io::DatabaseConnector;
    ///
    /// let connector = DatabaseConnector::new("sqlite://database.db");
    /// ```
    pub fn new(connection_string: &str) -> Self {
        Self {
            #[cfg(feature = "advanced_io")]
            connection_string: connection_string.to_string(),
            #[cfg(not(feature = "advanced_io"))]
            _phantom: std::marker::PhantomData,
        }
    }

    /// Execute a SQL query and return results as a DataFrame
    ///
    /// # Arguments
    ///
    /// * `query` - SQL query to execute
    ///
    /// # Returns
    ///
    /// DataFrame containing query results
    ///
    /// # Examples
    ///
    /// ```rust
    /// use veloxx::advanced_io::DatabaseConnector;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let connector = DatabaseConnector::new("sqlite://database.db");
    /// // let df = connector.query("SELECT * FROM users").await?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "advanced_io")]
    pub async fn query(&self, query: &str) -> Result<DataFrame, VeloxxError> {
        // Placeholder implementation - in a real implementation this would use self.connection_string
        let mut columns = indexmap::IndexMap::new();
        columns.insert(
            "query_result".to_string(),
            Series::new_string(
                "query_result",
                vec![Some(format!(
                    "Executed '{}' on {}",
                    query, self.connection_string
                ))],
            ),
        );

        Ok(DataFrame::new(columns))
    }

    #[cfg(not(feature = "advanced_io"))]
    pub async fn query(&self, _query: &str) -> Result<DataFrame, VeloxxError> {
        Err(VeloxxError::InvalidOperation(
            "Advanced I/O feature is not enabled. Enable with --features advanced_io".to_string(),
        ))
    }

    /// Insert a DataFrame into a database table
    ///
    /// # Arguments
    ///
    /// * `dataframe` - DataFrame to insert
    /// * `table_name` - Name of the target table
    ///
    /// # Examples
    ///
    /// ```rust
    /// use veloxx::dataframe::DataFrame;
    /// use veloxx::series::Series;
    /// use veloxx::advanced_io::DatabaseConnector;
    /// use indexmap::IndexMap;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut columns = IndexMap::new();
    /// columns.insert(
    ///     "id".to_string(),
    ///     Series::new_i32("id", vec![Some(1), Some(2)]),
    /// );
    ///
    /// let df = DataFrame::new(columns).unwrap();
    /// let connector = DatabaseConnector::new("sqlite://database.db");
    /// // connector.insert_dataframe(&df, "users").await?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "advanced_io")]
    pub async fn insert_dataframe(
        &self,
        _dataframe: &DataFrame,
        table_name: &str,
    ) -> Result<(), VeloxxError> {
        // Placeholder implementation - in a real implementation this would use self.connection_string
        println!(
            "Would insert DataFrame into table '{}' using connection: {}",
            table_name, self.connection_string
        );
        Ok(())
    }

    #[cfg(not(feature = "advanced_io"))]
    pub async fn insert_dataframe(
        &self,
        _dataframe: &DataFrame,
        _table_name: &str,
    ) -> Result<(), VeloxxError> {
        Err(VeloxxError::InvalidOperation(
            "Advanced I/O feature is not enabled. Enable with --features advanced_io".to_string(),
        ))
    }

    /// Create a table from a DataFrame schema
    ///
    /// # Arguments
    ///
    /// * `dataframe` - DataFrame to use for schema inference
    /// * `table_name` - Name of the table to create
    #[cfg(feature = "advanced_io")]
    pub async fn create_table_from_dataframe(
        &self,
        dataframe: &DataFrame,
        table_name: &str,
    ) -> Result<(), VeloxxError> {
        // Generate CREATE TABLE statement from DataFrame schema
        let mut create_sql = format!("CREATE TABLE {} (", table_name);
        let column_names = dataframe.column_names();

        for (i, column_name) in column_names.iter().enumerate() {
            if let Some(series) = dataframe.get_column(column_name) {
                let sql_type = match series.data_type() {
                    DataType::I32 => "INTEGER",
                    DataType::F64 => "REAL",
                    DataType::Bool => "BOOLEAN",
                    DataType::String => "TEXT",
                    DataType::DateTime => "DATETIME",
                };

                create_sql.push_str(&format!("{} {}", column_name, sql_type));
                if i < column_names.len() - 1 {
                    create_sql.push_str(", ");
                }
            }
        }
        create_sql.push(')');

        // In a real implementation, we would execute this SQL using self.connection_string
        println!(
            "Would execute on {}: {}",
            self.connection_string, create_sql
        );
        Ok(())
    }

    #[cfg(not(feature = "advanced_io"))]
    pub async fn create_table_from_dataframe(
        &self,
        _dataframe: &DataFrame,
        _table_name: &str,
    ) -> Result<(), VeloxxError> {
        Err(VeloxxError::InvalidOperation(
            "Advanced I/O feature is not enabled. Enable with --features advanced_io".to_string(),
        ))
    }
}

/// Async file operations for non-blocking I/O
pub struct AsyncFileOps;

impl AsyncFileOps {
    /// Read a CSV file asynchronously
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the CSV file
    ///
    /// # Returns
    ///
    /// DataFrame containing the CSV data
    #[cfg(feature = "advanced_io")]
    pub async fn read_csv_async<P: AsRef<Path>>(path: P) -> Result<DataFrame, VeloxxError> {
        let content = tokio::fs::read_to_string(path).await.map_err(|e| {
            VeloxxError::InvalidOperation(format!("Failed to read CSV file: {}", e))
        })?;

        // Parse CSV content from string
        Self::parse_csv_from_string(&content)
    }

    #[cfg(feature = "advanced_io")]
    fn parse_csv_from_string(content: &str) -> Result<DataFrame, VeloxxError> {
        let lines: Vec<&str> = content.lines().collect();
        if lines.is_empty() {
            return Err(VeloxxError::InvalidOperation(
                "CSV content is empty".to_string(),
            ));
        }

        // Parse header
        let header_line = lines[0];
        let column_names: Vec<String> = header_line
            .split(',')
            .map(|s| s.trim().to_string())
            .collect();

        // Parse data rows
        let mut data_rows: Vec<Vec<String>> = Vec::new();
        for line in &lines[1..] {
            let row: Vec<String> = line.split(',').map(|s| s.trim().to_string()).collect();
            data_rows.push(row);
        }

        DataFrame::from_vec_of_vec(data_rows, column_names)
    }

    #[cfg(not(feature = "advanced_io"))]
    pub async fn read_csv_async<P: AsRef<Path>>(_path: P) -> Result<DataFrame, VeloxxError> {
        Err(VeloxxError::InvalidOperation(
            "Advanced I/O feature is not enabled. Enable with --features advanced_io".to_string(),
        ))
    }

    /// Write a CSV file asynchronously
    ///
    /// # Arguments
    ///
    /// * `dataframe` - DataFrame to write
    /// * `path` - Path where the CSV file should be created
    #[cfg(feature = "advanced_io")]
    pub async fn write_csv_async<P: AsRef<Path>>(
        dataframe: &DataFrame,
        path: P,
    ) -> Result<(), VeloxxError> {
        // Generate CSV content as string
        let csv_content = Self::dataframe_to_csv_string(dataframe)?;
        tokio::fs::write(path, csv_content).await.map_err(|e| {
            VeloxxError::InvalidOperation(format!("Failed to write CSV file: {}", e))
        })?;

        Ok(())
    }

    #[cfg(feature = "advanced_io")]
    fn dataframe_to_csv_string(dataframe: &DataFrame) -> Result<String, VeloxxError> {
        let mut csv_content = String::new();

        // Write header
        let col_names_owned = dataframe.column_names();
        let column_names: Vec<&str> = col_names_owned.iter().map(|s| s.as_str()).collect();
        csv_content.push_str(&column_names.join(","));
        csv_content.push('\n');

        // Write data rows
        for i in 0..dataframe.row_count() {
            let mut row_values: Vec<String> = Vec::new();
            for col_name in column_names.iter() {
                let series = dataframe.get_column(col_name).unwrap();
                let value_str = match series.get_value(i) {
                    Some(crate::types::Value::I32(v)) => v.to_string(),
                    Some(crate::types::Value::F64(v)) => v.to_string(),
                    Some(crate::types::Value::Bool(v)) => v.to_string(),
                    Some(crate::types::Value::String(v)) => v,
                    Some(crate::types::Value::DateTime(v)) => v.to_string(),
                    Some(crate::types::Value::Null) => String::new(),
                    None => String::new(),
                };
                row_values.push(value_str);
            }
            csv_content.push_str(&row_values.join(","));
            csv_content.push('\n');
        }

        Ok(csv_content)
    }

    #[cfg(not(feature = "advanced_io"))]
    pub async fn write_csv_async<P: AsRef<Path>>(
        _dataframe: &DataFrame,
        _path: P,
    ) -> Result<(), VeloxxError> {
        Err(VeloxxError::InvalidOperation(
            "Advanced I/O feature is not enabled. Enable with --features advanced_io".to_string(),
        ))
    }

    /// Read a JSON file asynchronously
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the JSON file
    ///
    /// # Returns
    ///
    /// DataFrame containing the JSON data
    #[cfg(feature = "advanced_io")]
    pub async fn read_json_async<P: AsRef<Path>>(path: P) -> Result<DataFrame, VeloxxError> {
        let path_str = path.as_ref().to_string_lossy().to_string();
        tokio::task::spawn_blocking(move || {
            let parser = crate::io::json::UltraFastJsonParser::new();
            parser.read_file(&path_str)
        })
        .await
        .map_err(|e| VeloxxError::InvalidOperation(format!("Task join error: {}", e)))?
    }

    #[cfg(not(feature = "advanced_io"))]
    pub async fn read_json_async<P: AsRef<Path>>(_path: P) -> Result<DataFrame, VeloxxError> {
        Err(VeloxxError::InvalidOperation(
            "Advanced I/O feature is not enabled. Enable with --features advanced_io".to_string(),
        ))
    }

    /// Write a JSON file asynchronously
    ///
    /// # Arguments
    ///
    /// * `dataframe` - DataFrame to write
    /// * `path` - Path where the JSON file should be created
    #[cfg(feature = "advanced_io")]
    pub async fn write_json_async<P: AsRef<Path>>(
        dataframe: &DataFrame,
        path: P,
    ) -> Result<(), VeloxxError> {
        let json_content = Self::dataframe_to_json_string(dataframe)?;
        tokio::fs::write(path, json_content).await.map_err(|e| {
            VeloxxError::InvalidOperation(format!("Failed to write JSON file: {}", e))
        })?;

        Ok(())
    }

    #[cfg(feature = "advanced_io")]
    fn dataframe_to_json_string(dataframe: &DataFrame) -> Result<String, VeloxxError> {
        let mut json_content = String::from("[\n");

        for i in 0..dataframe.row_count() {
            if i > 0 {
                json_content.push_str(",\n");
            }
            json_content.push_str("  {");

            let mut first_field = true;
            for column_name in dataframe.column_names() {
                if !first_field {
                    json_content.push_str(", ");
                }
                first_field = false;

                let series = dataframe.get_column(&column_name).unwrap();
                json_content.push_str(&format!("\"{}\":", column_name));

                match series.get_value(i) {
                    Some(crate::types::Value::I32(v)) => json_content.push_str(&v.to_string()),
                    Some(crate::types::Value::F64(v)) => json_content.push_str(&v.to_string()),
                    Some(crate::types::Value::Bool(v)) => json_content.push_str(&v.to_string()),
                    Some(crate::types::Value::String(v)) => {
                        json_content.push_str(&format!("\"{}\"", v))
                    }
                    Some(crate::types::Value::DateTime(v)) => json_content.push_str(&v.to_string()),
                    Some(crate::types::Value::Null) => json_content.push_str("null"),
                    None => json_content.push_str("null"),
                }
            }

            json_content.push('}');
        }

        json_content.push_str("\n]");
        Ok(json_content)
    }

    #[cfg(not(feature = "advanced_io"))]
    pub async fn write_json_async<P: AsRef<Path>>(
        _dataframe: &DataFrame,
        _path: P,
    ) -> Result<(), VeloxxError> {
        Err(VeloxxError::InvalidOperation(
            "Advanced I/O feature is not enabled. Enable with --features advanced_io".to_string(),
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parquet_reader_creation() {
        let reader = ParquetReader::new();
        // Just test that we can create the reader
        assert_eq!(
            std::mem::size_of_val(&reader),
            std::mem::size_of::<ParquetReader>()
        );
    }

    #[test]
    fn test_parquet_writer_creation() {
        let writer = ParquetWriter::new();
        // Just test that we can create the writer
        assert_eq!(
            std::mem::size_of_val(&writer),
            std::mem::size_of::<ParquetWriter>()
        );
    }

    #[test]
    fn test_json_streamer_creation() {
        let streamer = JsonStreamer::new();
        // Just test that we can create the streamer
        assert_eq!(
            std::mem::size_of_val(&streamer),
            std::mem::size_of::<JsonStreamer>()
        );
    }

    #[test]
    fn test_database_connector_creation() {
        let connector = DatabaseConnector::new("sqlite://test.db");
        // Just test that we can create the connector
        assert_eq!(
            std::mem::size_of_val(&connector),
            std::mem::size_of::<DatabaseConnector>()
        );
    }

    #[tokio::test]
    async fn test_advanced_io_without_feature() {
        let reader = ParquetReader::new();
        let result = reader.read_dataframe("test.parquet").await;

        #[cfg(not(feature = "advanced_io"))]
        assert!(result.is_err());

        #[cfg(feature = "advanced_io")]
        {
            // Would test actual functionality with feature enabled
            let _ = result;
        }
    }
}