exarrow-rs 0.12.0

ADBC-compatible driver for Exasol with Arrow data format support
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
//! Import query builder for generating IMPORT SQL statements.
//!
//! This module provides a builder pattern for constructing Exasol IMPORT statements
//! that import data from HTTP endpoints into database tables.
//!
//! # Example
//!

/// Row separator options for CSV import.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RowSeparator {
    /// Line feed (Unix-style)
    #[default]
    LF,
    /// Carriage return (old Mac-style)
    CR,
    /// Carriage return + line feed (Windows-style)
    CRLF,
}

impl RowSeparator {
    /// Convert to SQL string representation.
    pub fn to_sql(&self) -> &'static str {
        match self {
            RowSeparator::LF => "LF",
            RowSeparator::CR => "CR",
            RowSeparator::CRLF => "CRLF",
        }
    }
}

/// Compression options for import files.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Compression {
    /// No compression
    #[default]
    None,
    /// Gzip compression (.gz extension)
    Gzip,
    /// Bzip2 compression (.bz2 extension)
    Bzip2,
}

impl Compression {
    /// Get the file extension for this compression type.
    pub fn extension(&self) -> &'static str {
        match self {
            Compression::None => ".csv",
            Compression::Gzip => ".csv.gz",
            Compression::Bzip2 => ".csv.bz2",
        }
    }
}

/// File format for an IMPORT statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ImportFormat {
    /// CSV format. Format options (encoding, separators, etc.) apply.
    #[default]
    Csv,
    /// Native Parquet format. The server detects the schema from the file;
    /// CSV format options and compression suffixes do not apply.
    Parquet,
}

/// Trim mode options for CSV import.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TrimMode {
    /// No trimming
    #[default]
    None,
    /// Trim leading whitespace
    LTrim,
    /// Trim trailing whitespace
    RTrim,
    /// Trim both leading and trailing whitespace
    Trim,
}

impl TrimMode {
    /// Convert to SQL string representation.
    pub fn to_sql(&self) -> Option<&'static str> {
        match self {
            TrimMode::None => None,
            TrimMode::LTrim => Some("LTRIM"),
            TrimMode::RTrim => Some("RTRIM"),
            TrimMode::Trim => Some("TRIM"),
        }
    }
}

/// Entry for a single file in a multi-file IMPORT statement.
///
/// Used with `ImportQuery::with_files()` to build IMPORT statements
/// that reference multiple FILE clauses for parallel import.
#[derive(Debug, Clone)]
pub struct ImportFileEntry {
    /// Internal address from EXA handshake (format: "host:port")
    pub address: String,
    /// File name for this entry (e.g., "001.csv", "002.csv")
    pub file_name: String,
    /// Optional public key fingerprint for TLS
    pub public_key: Option<String>,
}

impl ImportFileEntry {
    /// Create a new import file entry.
    ///
    /// # Arguments
    ///
    /// * `address` - Internal address from EXA handshake
    /// * `file_name` - File name for this entry
    /// * `public_key` - Optional public key fingerprint for TLS
    pub fn new(address: String, file_name: String, public_key: Option<String>) -> Self {
        Self {
            address,
            file_name,
            public_key,
        }
    }
}

/// Builder for constructing Exasol IMPORT SQL statements.
///
/// The ImportQuery builder allows you to configure all aspects of an IMPORT statement
/// including the target table, columns, CSV format options, and error handling.
///
/// # Multi-file Import
///
/// For parallel imports, use `with_files()` instead of `at_address()` and `file_name()`:
///
/// ```rust
/// use exarrow_rs::query::import::{ImportQuery, ImportFileEntry};
///
/// let entries = vec![
///     ImportFileEntry::new("10.0.0.5:8563".to_string(), "001.csv".to_string(), None),
///     ImportFileEntry::new("10.0.0.6:8563".to_string(), "002.csv".to_string(), None),
/// ];
///
/// let query = ImportQuery::new("my_table")
///     .with_files(entries)
///     .build();
/// ```
#[derive(Debug, Clone)]
pub struct ImportQuery {
    /// Target table name (required)
    table: String,
    /// Target schema (optional)
    schema: Option<String>,
    /// Columns to import into (optional, imports all if not specified)
    columns: Option<Vec<String>>,
    /// HTTP address for the CSV source (e.g., "192.168.1.1:8080") - single file mode
    address: Option<String>,
    /// SHA-256 fingerprint for TLS public key verification - single file mode
    public_key: Option<String>,
    /// File name (default "001.csv") - single file mode
    file_name: String,
    /// Multiple file entries for parallel import
    file_entries: Option<Vec<ImportFileEntry>>,
    /// Column separator character (default ',')
    column_separator: char,
    /// Column delimiter character for quoting (default '"')
    column_delimiter: char,
    /// Row separator (default LF)
    row_separator: RowSeparator,
    /// Character encoding (default "UTF-8")
    encoding: String,
    /// Number of header rows to skip (default 0)
    skip: u32,
    /// Custom NULL value representation
    null_value: Option<String>,
    /// Trim mode for values
    trim: TrimMode,
    /// Compression type
    compression: Compression,
    /// Maximum number of invalid rows before failure
    reject_limit: Option<u32>,
    /// File format (CSV or Parquet)
    format: ImportFormat,
}

impl ImportQuery {
    /// Create a new ImportQuery builder for the specified table.
    ///
    /// # Arguments
    /// * `table` - The name of the target table to import into
    ///
    pub fn new(table: &str) -> Self {
        Self {
            table: table.to_string(),
            schema: None,
            columns: None,
            address: None,
            public_key: None,
            file_name: "001.csv".to_string(),
            file_entries: None,
            column_separator: ',',
            column_delimiter: '"',
            row_separator: RowSeparator::default(),
            encoding: "UTF-8".to_string(),
            skip: 0,
            null_value: None,
            trim: TrimMode::default(),
            compression: Compression::default(),
            reject_limit: None,
            format: ImportFormat::default(),
        }
    }

    /// Set the target schema for the import.
    ///
    /// # Arguments
    /// * `schema` - The schema name
    pub fn schema(mut self, schema: &str) -> Self {
        self.schema = Some(schema.to_string());
        self
    }

    /// Set the columns to import into.
    ///
    /// If not specified, all columns in the table will be used.
    ///
    /// # Arguments
    /// * `cols` - List of column names
    pub fn columns(mut self, cols: Vec<&str>) -> Self {
        self.columns = Some(cols.into_iter().map(String::from).collect());
        self
    }

    /// Set the HTTP address to import from.
    ///
    /// # Arguments
    /// * `addr` - HTTP address in "host:port" format
    pub fn at_address(mut self, addr: &str) -> Self {
        self.address = Some(addr.to_string());
        self
    }

    /// Set the public key fingerprint for TLS verification.
    ///
    /// When set, HTTPS will be used and the PUBLIC KEY clause will be added.
    ///
    /// # Arguments
    /// * `fingerprint` - SHA-256 fingerprint of the server's public key
    pub fn with_public_key(mut self, fingerprint: &str) -> Self {
        self.public_key = Some(fingerprint.to_string());
        self
    }

    /// Set the file name for the import.
    ///
    /// # Arguments
    /// * `name` - File name (default "001.csv")
    pub fn file_name(mut self, name: &str) -> Self {
        self.file_name = name.to_string();
        self
    }

    /// Set the column separator character.
    ///
    /// # Arguments
    /// * `sep` - Separator character (default ',')
    pub fn column_separator(mut self, sep: char) -> Self {
        self.column_separator = sep;
        self
    }

    /// Set the column delimiter character for quoting.
    ///
    /// # Arguments
    /// * `delim` - Delimiter character (default '"')
    pub fn column_delimiter(mut self, delim: char) -> Self {
        self.column_delimiter = delim;
        self
    }

    /// Set the row separator.
    ///
    /// # Arguments
    /// * `sep` - Row separator (default LF)
    pub fn row_separator(mut self, sep: RowSeparator) -> Self {
        self.row_separator = sep;
        self
    }

    /// Set the character encoding.
    ///
    /// # Arguments
    /// * `enc` - Encoding name (default "UTF-8")
    pub fn encoding(mut self, enc: &str) -> Self {
        self.encoding = enc.to_string();
        self
    }

    /// Set the number of header rows to skip.
    ///
    /// # Arguments
    /// * `rows` - Number of rows to skip (default 0)
    pub fn skip(mut self, rows: u32) -> Self {
        self.skip = rows;
        self
    }

    /// Set a custom NULL value representation.
    ///
    /// # Arguments
    /// * `val` - String representing NULL values in the CSV
    pub fn null_value(mut self, val: &str) -> Self {
        self.null_value = Some(val.to_string());
        self
    }

    /// Set the trim mode for imported values.
    ///
    /// # Arguments
    /// * `trim` - Trim mode to apply
    pub fn trim(mut self, trim: TrimMode) -> Self {
        self.trim = trim;
        self
    }

    /// Set the compression type for the import file.
    ///
    /// This affects the file extension in the generated SQL.
    ///
    /// # Arguments
    /// * `compression` - Compression type
    pub fn compressed(mut self, compression: Compression) -> Self {
        self.compression = compression;
        self
    }

    /// Set the reject limit for error handling.
    ///
    /// # Arguments
    /// * `limit` - Maximum number of invalid rows before the import fails
    pub fn reject_limit(mut self, limit: u32) -> Self {
        self.reject_limit = Some(limit);
        self
    }

    /// Set the file format for the import.
    ///
    /// When set to `ImportFormat::Parquet`, the generated SQL emits
    /// `FROM PARQUET`, the file extension becomes `.parquet` regardless of
    /// the configured compression, and the CSV format-options clause is
    /// omitted (the server reads the schema from the Parquet file).
    ///
    /// # Arguments
    /// * `format` - File format
    pub fn with_format(mut self, format: ImportFormat) -> Self {
        self.format = format;
        self
    }

    /// Set multiple file entries for parallel import.
    ///
    /// This method enables multi-file IMPORT statements where each file
    /// has its own AT/FILE clause with a unique internal address.
    ///
    /// # Arguments
    /// * `entries` - Vector of file entries with addresses and file names
    ///
    /// # Note
    ///
    /// When using `with_files()`, the `at_address()` and `file_name()` methods
    /// are ignored and should not be called.
    pub fn with_files(mut self, entries: Vec<ImportFileEntry>) -> Self {
        self.file_entries = Some(entries);
        self
    }

    /// Get the configured file name with the appropriate extension.
    ///
    /// For `ImportFormat::Parquet`, the extension is always `.parquet` and
    /// any configured compression suffix is bypassed. For `ImportFormat::Csv`,
    /// the extension reflects the configured `Compression`.
    fn get_file_name(&self) -> String {
        let base_name = strip_known_extensions(&self.file_name);
        match self.format {
            ImportFormat::Parquet => format!("{}.parquet", base_name),
            ImportFormat::Csv => format!("{}{}", base_name, self.compression.extension()),
        }
    }

    /// Build the complete IMPORT SQL statement.
    ///
    /// # Returns
    /// The generated IMPORT SQL statement as a string.
    ///
    pub fn build(&self) -> String {
        let mut sql = String::with_capacity(512);

        // IMPORT INTO clause
        sql.push_str("IMPORT INTO ");
        if let Some(ref schema) = self.schema {
            sql.push_str(schema);
            sql.push('.');
        }
        sql.push_str(&self.table);

        // Column list
        if let Some(ref cols) = self.columns {
            sql.push_str(" (");
            sql.push_str(&cols.join(", "));
            sql.push(')');
        }

        // FROM <FORMAT> clause - either multi-file or single-file mode.
        // The format keyword (CSV vs PARQUET) and per-URL suffix differ;
        // the rest of the address/PUBLIC KEY/FILE structure is shared.
        let is_parquet = matches!(self.format, ImportFormat::Parquet);
        let format_keyword = if is_parquet { "PARQUET" } else { "CSV" };

        if let Some(ref entries) = self.file_entries {
            // Multi-file mode: FROM <FORMAT> AT 'addr1' FILE '001.csv' AT 'addr2' FILE '002.csv' ...
            sql.push_str("\nFROM ");
            sql.push_str(format_keyword);

            for entry in entries {
                sql.push_str(" AT '");

                // Use https:// if public_key is set, otherwise http://
                if entry.public_key.is_some() {
                    sql.push_str("https://");
                } else {
                    sql.push_str("http://");
                }
                sql.push_str(&entry.address);
                // The `;MaxConcurrentReads=1` suffix is appended INSIDE the
                // quoted URL string for native Parquet imports, mirroring the
                // JDBC reference driver's on-the-wire shape.
                if is_parquet {
                    sql.push_str(";MaxConcurrentReads=1");
                }
                sql.push('\'');

                // PUBLIC KEY clause for this entry
                if let Some(ref pk) = entry.public_key {
                    sql.push_str(" PUBLIC KEY '");
                    sql.push_str(pk);
                    sql.push('\'');
                }

                // FILE clause for this entry
                sql.push_str(" FILE '");
                sql.push_str(&self.get_file_name_for(&entry.file_name));
                sql.push('\'');
            }
        } else {
            // Single-file mode: FROM <FORMAT> AT 'addr' FILE '001.csv'
            sql.push_str("\nFROM ");
            sql.push_str(format_keyword);
            sql.push_str(" AT '");

            // Use https:// if public_key is set, otherwise http://
            if self.public_key.is_some() {
                sql.push_str("https://");
            } else {
                sql.push_str("http://");
            }

            if let Some(ref addr) = self.address {
                sql.push_str(addr);
            }
            // The `;MaxConcurrentReads=1` suffix is appended INSIDE the
            // quoted URL string for native Parquet imports.
            if is_parquet {
                sql.push_str(";MaxConcurrentReads=1");
            }
            sql.push('\'');

            // PUBLIC KEY clause
            if let Some(ref pk) = self.public_key {
                sql.push_str(" PUBLIC KEY '");
                sql.push_str(pk);
                sql.push('\'');
            }

            // FILE clause
            sql.push_str("\nFILE '");
            sql.push_str(&self.get_file_name());
            sql.push('\'');
        }

        // Format options apply ONLY to CSV. For PARQUET the server reads the
        // schema from the file directly, so emitting any of these clauses
        // (ENCODING, COLUMN SEPARATOR, COLUMN DELIMITER, ROW SEPARATOR, SKIP,
        // NULL, TRIM, REJECT LIMIT) would either be rejected or ignored.
        if !is_parquet {
            sql.push_str("\nENCODING = '");
            sql.push_str(&self.encoding);
            sql.push('\'');

            sql.push_str("\nCOLUMN SEPARATOR = '");
            sql.push(self.column_separator);
            sql.push('\'');

            sql.push_str("\nCOLUMN DELIMITER = '");
            sql.push(self.column_delimiter);
            sql.push('\'');

            sql.push_str("\nROW SEPARATOR = '");
            sql.push_str(self.row_separator.to_sql());
            sql.push('\'');

            // Optional SKIP
            if self.skip > 0 {
                sql.push_str("\nSKIP = ");
                sql.push_str(&self.skip.to_string());
            }

            // Optional NULL value
            if let Some(ref null_val) = self.null_value {
                sql.push_str("\nNULL = '");
                sql.push_str(null_val);
                sql.push('\'');
            }

            // Optional TRIM
            if let Some(trim_sql) = self.trim.to_sql() {
                sql.push_str("\nTRIM = '");
                sql.push_str(trim_sql);
                sql.push('\'');
            }

            // Optional REJECT LIMIT
            if let Some(limit) = self.reject_limit {
                sql.push_str("\nREJECT LIMIT ");
                sql.push_str(&limit.to_string());
            }
        }

        sql
    }

    /// Get file name with the appropriate extension for multi-file entries.
    ///
    /// Mirrors `get_file_name`'s format-aware extension policy.
    fn get_file_name_for(&self, base_name: &str) -> String {
        let base = strip_known_extensions(base_name);
        match self.format {
            ImportFormat::Parquet => format!("{}.parquet", base),
            ImportFormat::Csv => format!("{}{}", base, self.compression.extension()),
        }
    }
}

fn strip_known_extensions(name: &str) -> &str {
    let mut current = name;
    loop {
        let stripped = current
            .strip_suffix(".gz")
            .or_else(|| current.strip_suffix(".bz2"))
            .or_else(|| current.strip_suffix(".csv"))
            .or_else(|| current.strip_suffix(".parquet"));
        match stripped {
            Some(next) if next.len() < current.len() => current = next,
            _ => return current,
        }
    }
}

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

    #[test]
    fn test_basic_import_statement() {
        let sql = ImportQuery::new("users")
            .at_address("192.168.1.1:8080")
            .build();

        assert!(sql.contains("IMPORT INTO users"));
        assert!(sql.contains("FROM CSV AT 'http://192.168.1.1:8080'"));
        assert!(sql.contains("FILE '001.csv'"));
        assert!(sql.contains("ENCODING = 'UTF-8'"));
        assert!(sql.contains("COLUMN SEPARATOR = ','"));
        assert!(sql.contains("COLUMN DELIMITER = '\"'"));
        assert!(sql.contains("ROW SEPARATOR = 'LF'"));
    }

    #[test]
    fn test_import_with_schema() {
        let sql = ImportQuery::new("users")
            .schema("myschema")
            .at_address("192.168.1.1:8080")
            .build();

        assert!(sql.contains("IMPORT INTO myschema.users"));
    }

    #[test]
    fn test_import_with_columns() {
        let sql = ImportQuery::new("users")
            .columns(vec!["id", "name", "email"])
            .at_address("192.168.1.1:8080")
            .build();

        assert!(sql.contains("IMPORT INTO users (id, name, email)"));
    }

    #[test]
    fn test_import_with_all_format_options() {
        let sql = ImportQuery::new("data")
            .at_address("10.0.0.1:9000")
            .column_separator(';')
            .column_delimiter('\'')
            .row_separator(RowSeparator::CRLF)
            .encoding("ISO-8859-1")
            .skip(2)
            .null_value("NULL")
            .trim(TrimMode::Trim)
            .reject_limit(100)
            .build();

        assert!(sql.contains("COLUMN SEPARATOR = ';'"));
        assert!(sql.contains("COLUMN DELIMITER = '''"));
        assert!(sql.contains("ROW SEPARATOR = 'CRLF'"));
        assert!(sql.contains("ENCODING = 'ISO-8859-1'"));
        assert!(sql.contains("SKIP = 2"));
        assert!(sql.contains("NULL = 'NULL'"));
        assert!(sql.contains("TRIM = 'TRIM'"));
        assert!(sql.contains("REJECT LIMIT 100"));
    }

    #[test]
    fn test_import_with_use_tls() {
        let fingerprint = "SHA256:abc123def456";
        let sql = ImportQuery::new("secure_data")
            .at_address("192.168.1.1:8443")
            .with_public_key(fingerprint)
            .build();

        assert!(sql.contains("FROM CSV AT 'https://192.168.1.1:8443'"));
        assert!(sql.contains(&format!("PUBLIC KEY '{}'", fingerprint)));
    }

    #[test]
    fn test_import_with_gzip_compression() {
        let sql = ImportQuery::new("compressed_data")
            .at_address("192.168.1.1:8080")
            .compressed(Compression::Gzip)
            .build();

        assert!(sql.contains("FILE '001.csv.gz'"));
    }

    #[test]
    fn test_import_with_bzip2_compression() {
        let sql = ImportQuery::new("compressed_data")
            .at_address("192.168.1.1:8080")
            .compressed(Compression::Bzip2)
            .build();

        assert!(sql.contains("FILE '001.csv.bz2'"));
    }

    #[test]
    fn test_import_custom_file_name() {
        let sql = ImportQuery::new("data")
            .at_address("192.168.1.1:8080")
            .file_name("custom_file")
            .build();

        assert!(sql.contains("FILE 'custom_file.csv'"));
    }

    #[test]
    fn test_import_custom_file_name_with_compression() {
        let sql = ImportQuery::new("data")
            .at_address("192.168.1.1:8080")
            .file_name("custom_file")
            .compressed(Compression::Gzip)
            .build();

        assert!(sql.contains("FILE 'custom_file.csv.gz'"));
    }

    #[test]
    fn test_row_separator_to_sql() {
        assert_eq!(RowSeparator::LF.to_sql(), "LF");
        assert_eq!(RowSeparator::CR.to_sql(), "CR");
        assert_eq!(RowSeparator::CRLF.to_sql(), "CRLF");
    }

    #[test]
    fn test_compression_extension() {
        assert_eq!(Compression::None.extension(), ".csv");
        assert_eq!(Compression::Gzip.extension(), ".csv.gz");
        assert_eq!(Compression::Bzip2.extension(), ".csv.bz2");
    }

    #[test]
    fn test_trim_mode_to_sql() {
        assert_eq!(TrimMode::None.to_sql(), None);
        assert_eq!(TrimMode::LTrim.to_sql(), Some("LTRIM"));
        assert_eq!(TrimMode::RTrim.to_sql(), Some("RTRIM"));
        assert_eq!(TrimMode::Trim.to_sql(), Some("TRIM"));
    }

    #[test]
    fn test_defaults() {
        assert_eq!(RowSeparator::default(), RowSeparator::LF);
        assert_eq!(Compression::default(), Compression::None);
        assert_eq!(TrimMode::default(), TrimMode::None);
    }

    #[test]
    fn test_import_file_entry() {
        let entry = ImportFileEntry::new(
            "10.0.0.5:8563".to_string(),
            "001.csv".to_string(),
            Some("sha256//abc123".to_string()),
        );

        assert_eq!(entry.address, "10.0.0.5:8563");
        assert_eq!(entry.file_name, "001.csv");
        assert_eq!(entry.public_key, Some("sha256//abc123".to_string()));
    }

    #[test]
    fn test_multi_file_import_basic() {
        let entries = vec![
            ImportFileEntry::new("10.0.0.5:8563".to_string(), "001.csv".to_string(), None),
            ImportFileEntry::new("10.0.0.6:8564".to_string(), "002.csv".to_string(), None),
        ];

        let sql = ImportQuery::new("my_table").with_files(entries).build();

        assert!(sql.contains("IMPORT INTO my_table"));
        assert!(sql.contains("FROM CSV"));
        assert!(sql.contains("AT 'http://10.0.0.5:8563' FILE '001.csv'"));
        assert!(sql.contains("AT 'http://10.0.0.6:8564' FILE '002.csv'"));
    }

    #[test]
    fn test_multi_file_import_with_tls() {
        let entries = vec![
            ImportFileEntry::new(
                "10.0.0.5:8563".to_string(),
                "001.csv".to_string(),
                Some("sha256//fingerprint1".to_string()),
            ),
            ImportFileEntry::new(
                "10.0.0.6:8564".to_string(),
                "002.csv".to_string(),
                Some("sha256//fingerprint2".to_string()),
            ),
        ];

        let sql = ImportQuery::new("secure_table").with_files(entries).build();

        assert!(sql.contains("AT 'https://10.0.0.5:8563' PUBLIC KEY 'sha256//fingerprint1'"));
        assert!(sql.contains("AT 'https://10.0.0.6:8564' PUBLIC KEY 'sha256//fingerprint2'"));
    }

    #[test]
    fn test_multi_file_import_with_compression() {
        let entries = vec![
            ImportFileEntry::new("10.0.0.5:8563".to_string(), "001.csv".to_string(), None),
            ImportFileEntry::new("10.0.0.6:8564".to_string(), "002.csv".to_string(), None),
        ];

        let sql = ImportQuery::new("compressed_table")
            .with_files(entries)
            .compressed(Compression::Gzip)
            .build();

        assert!(sql.contains("FILE '001.csv.gz'"));
        assert!(sql.contains("FILE '002.csv.gz'"));
    }

    #[test]
    fn test_multi_file_import_three_files() {
        let entries = vec![
            ImportFileEntry::new("10.0.0.5:8563".to_string(), "001.csv".to_string(), None),
            ImportFileEntry::new("10.0.0.6:8564".to_string(), "002.csv".to_string(), None),
            ImportFileEntry::new("10.0.0.7:8565".to_string(), "003.csv".to_string(), None),
        ];

        let sql = ImportQuery::new("data").with_files(entries).build();

        assert!(sql.contains("AT 'http://10.0.0.5:8563' FILE '001.csv'"));
        assert!(sql.contains("AT 'http://10.0.0.6:8564' FILE '002.csv'"));
        assert!(sql.contains("AT 'http://10.0.0.7:8565' FILE '003.csv'"));
    }

    #[test]
    fn test_multi_file_import_with_schema_and_columns() {
        let entries = vec![
            ImportFileEntry::new("10.0.0.5:8563".to_string(), "001.csv".to_string(), None),
            ImportFileEntry::new("10.0.0.6:8564".to_string(), "002.csv".to_string(), None),
        ];

        let sql = ImportQuery::new("my_table")
            .schema("my_schema")
            .columns(vec!["id", "name", "value"])
            .with_files(entries)
            .build();

        assert!(sql.contains("IMPORT INTO my_schema.my_table (id, name, value)"));
    }

    #[test]
    fn test_multi_file_import_with_all_options() {
        let entries = vec![
            ImportFileEntry::new("10.0.0.5:8563".to_string(), "001.csv".to_string(), None),
            ImportFileEntry::new("10.0.0.6:8564".to_string(), "002.csv".to_string(), None),
        ];

        let sql = ImportQuery::new("data")
            .with_files(entries)
            .encoding("ISO-8859-1")
            .column_separator(';')
            .skip(1)
            .null_value("NULL")
            .reject_limit(100)
            .build();

        assert!(sql.contains("ENCODING = 'ISO-8859-1'"));
        assert!(sql.contains("COLUMN SEPARATOR = ';'"));
        assert!(sql.contains("SKIP = 1"));
        assert!(sql.contains("NULL = 'NULL'"));
        assert!(sql.contains("REJECT LIMIT 100"));
    }

    #[test]
    fn test_import_no_skip_when_zero() {
        let sql = ImportQuery::new("data")
            .at_address("192.168.1.1:8080")
            .build();

        // SKIP should not appear when it's 0
        assert!(!sql.contains("SKIP"));
    }

    #[test]
    fn test_import_skip_header_row() {
        let sql = ImportQuery::new("data")
            .at_address("192.168.1.1:8080")
            .skip(1)
            .build();

        assert!(sql.contains("SKIP = 1"));
    }

    #[test]
    fn test_complete_import_statement_format() {
        let sql = ImportQuery::new("employees")
            .schema("hr")
            .columns(vec!["id", "first_name", "last_name", "department"])
            .at_address("10.20.30.40:8080")
            .with_public_key("SHA256:fingerprint123")
            .skip(1)
            .reject_limit(10)
            .build();

        // Verify the complete structure
        let expected_parts = [
            "IMPORT INTO hr.employees (id, first_name, last_name, department)",
            "FROM CSV AT 'https://10.20.30.40:8080' PUBLIC KEY 'SHA256:fingerprint123'",
            "FILE '001.csv'",
            "ENCODING = 'UTF-8'",
            "COLUMN SEPARATOR = ','",
            "COLUMN DELIMITER = '\"'",
            "ROW SEPARATOR = 'LF'",
            "SKIP = 1",
            "REJECT LIMIT 10",
        ];

        for part in expected_parts {
            assert!(sql.contains(part), "SQL should contain: {}", part);
        }
    }

    #[test]
    fn test_import_query_format_parquet_single_file() {
        let sql = ImportQuery::new("my_table")
            .at_address("10.0.0.5:8563")
            .with_format(ImportFormat::Parquet)
            .build();
        assert!(sql.contains("FROM PARQUET AT 'http://10.0.0.5:8563;MaxConcurrentReads=1'"));
        assert!(sql.contains("FILE '001.parquet'"));
        assert!(!sql.contains("ENCODING"));
    }

    #[test]
    fn test_import_query_format_parquet_multi_file() {
        let entries = vec![
            ImportFileEntry::new("10.0.0.5:8563".to_string(), "001.parquet".to_string(), None),
            ImportFileEntry::new("10.0.0.6:8564".to_string(), "002.parquet".to_string(), None),
        ];
        let sql = ImportQuery::new("my_table")
            .with_files(entries)
            .with_format(ImportFormat::Parquet)
            .build();
        assert!(sql.contains("FROM PARQUET"));
        assert!(sql.contains("AT 'http://10.0.0.5:8563;MaxConcurrentReads=1'"));
        assert!(sql.contains("AT 'http://10.0.0.6:8564;MaxConcurrentReads=1'"));
        assert!(sql.contains("FILE '001.parquet'"));
        assert!(sql.contains("FILE '002.parquet'"));
        assert!(!sql.contains("MULTIPLE LOCAL FILES"));
    }

    #[test]
    fn test_import_query_format_parquet_with_tls_emits_public_key() {
        let sql = ImportQuery::new("t")
            .at_address("10.0.0.5:8563")
            .with_public_key("sha256//abc")
            .with_format(ImportFormat::Parquet)
            .build();
        assert!(sql
            .contains("AT 'https://10.0.0.5:8563;MaxConcurrentReads=1' PUBLIC KEY 'sha256//abc'"));
    }

    #[test]
    fn test_import_query_format_parquet_omits_csv_format_options() {
        let sql = ImportQuery::new("t")
            .at_address("addr:1234")
            .with_format(ImportFormat::Parquet)
            .skip(2)
            .null_value("NULL")
            .trim(TrimMode::Trim)
            .reject_limit(100)
            .build();
        for keyword in &[
            "ENCODING",
            "COLUMN SEPARATOR",
            "COLUMN DELIMITER",
            "ROW SEPARATOR",
            "SKIP",
            "NULL",
            "TRIM",
            "REJECT LIMIT",
        ] {
            assert!(
                !sql.contains(keyword),
                "SQL should NOT contain {} for Parquet format",
                keyword
            );
        }
    }

    #[test]
    fn test_import_query_parquet_ignores_compression() {
        let sql = ImportQuery::new("t")
            .at_address("addr:1234")
            .with_format(ImportFormat::Parquet)
            .compressed(Compression::Gzip)
            .build();
        assert!(sql.contains("FILE '001.parquet'"));
        assert!(!sql.contains(".gz"));
    }

    #[test]
    fn test_import_query_format_csv_unchanged() {
        let sql = ImportQuery::new("t").at_address("192.168.1.1:8080").build();
        assert!(sql.contains("FROM CSV AT 'http://192.168.1.1:8080'"));
        assert!(sql.contains("ENCODING = 'UTF-8'"));
        assert!(sql.contains("COLUMN SEPARATOR = ','"));
    }
}