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
//! Export query builder for generating EXPORT SQL statements.
//!
//! This module provides the `ExportQuery` builder for constructing Exasol EXPORT statements
//! that export data to an HTTP endpoint via CSV format.
//!
//! # Example
//!

/// Row separator options for CSV export.
#[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 {
    /// Get the SQL representation of the row separator.
    pub fn as_sql(&self) -> &'static str {
        match self {
            RowSeparator::LF => "LF",
            RowSeparator::CR => "CR",
            RowSeparator::CRLF => "CRLF",
        }
    }
}

/// Compression options for export 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 the compression type.
    pub fn extension(&self) -> &'static str {
        match self {
            Compression::None => "",
            Compression::Gzip => ".gz",
            Compression::Bzip2 => ".bz2",
        }
    }
}

/// Delimit mode for CSV export.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DelimitMode {
    /// Automatically detect when delimiters are needed
    #[default]
    Auto,
    /// Always use delimiters
    Always,
    /// Never use delimiters
    Never,
}

impl DelimitMode {
    /// Get the SQL representation of the delimit mode.
    pub fn as_sql(&self) -> &'static str {
        match self {
            DelimitMode::Auto => "AUTO",
            DelimitMode::Always => "ALWAYS",
            DelimitMode::Never => "NEVER",
        }
    }
}

/// Source for the export: either a table or a query.
#[derive(Debug, Clone)]
pub enum ExportSource {
    /// Export from a table.
    Table {
        /// Schema name (optional).
        schema: Option<String>,
        /// Table name.
        name: String,
        /// Columns to export (optional, empty means all columns).
        columns: Vec<String>,
    },
    /// Export from a query.
    Query {
        /// SQL query to export results from.
        sql: String,
    },
}

/// Builder for constructing EXPORT SQL statements.
///
/// Exasol EXPORT statements transfer data from tables or queries to external destinations
/// via HTTP transport using CSV format.
#[derive(Debug, Clone)]
pub struct ExportQuery {
    /// Source of the export (table or query).
    source: ExportSource,
    /// HTTP address for the export destination.
    address: String,
    /// Public key fingerprint for TLS (optional).
    public_key: Option<String>,
    /// File name for the export.
    file_name: String,
    /// Column separator character.
    column_separator: char,
    /// Column delimiter character.
    column_delimiter: char,
    /// Row separator.
    row_separator: RowSeparator,
    /// Character encoding.
    encoding: String,
    /// Custom NULL representation (optional).
    null_value: Option<String>,
    /// Delimit mode.
    delimit_mode: DelimitMode,
    /// Compression type.
    compression: Compression,
    /// Whether to include column names in the output.
    with_column_names: bool,
}

impl ExportQuery {
    /// Create an export query from a table.
    ///
    /// # Arguments
    ///
    /// * `table` - The name of the table to export from.
    ///
    /// # Example
    ///
    pub fn from_table(table: &str) -> Self {
        Self {
            source: ExportSource::Table {
                schema: None,
                name: table.to_string(),
                columns: Vec::new(),
            },
            address: String::new(),
            public_key: None,
            file_name: "001.csv".to_string(),
            column_separator: ',',
            column_delimiter: '"',
            row_separator: RowSeparator::default(),
            encoding: "UTF-8".to_string(),
            null_value: None,
            delimit_mode: DelimitMode::default(),
            compression: Compression::default(),
            with_column_names: false,
        }
    }

    /// Create an export query from a SQL query.
    ///
    /// # Arguments
    ///
    /// * `sql` - The SQL query whose results to export.
    ///
    /// # Example
    ///
    pub fn from_query(sql: &str) -> Self {
        Self {
            source: ExportSource::Query {
                sql: sql.to_string(),
            },
            address: String::new(),
            public_key: None,
            file_name: "001.csv".to_string(),
            column_separator: ',',
            column_delimiter: '"',
            row_separator: RowSeparator::default(),
            encoding: "UTF-8".to_string(),
            null_value: None,
            delimit_mode: DelimitMode::default(),
            compression: Compression::default(),
            with_column_names: false,
        }
    }

    /// Set the schema for a table export.
    ///
    /// This method only has an effect when exporting from a table, not from a query.
    ///
    /// # Arguments
    ///
    /// * `schema` - The schema name.
    pub fn schema(mut self, schema: &str) -> Self {
        if let ExportSource::Table {
            schema: ref mut s, ..
        } = self.source
        {
            *s = Some(schema.to_string());
        }
        self
    }

    /// Set the columns to export from a table.
    ///
    /// This method only has an effect when exporting from a table, not from a query.
    ///
    /// # Arguments
    ///
    /// * `cols` - The column names to export.
    pub fn columns(mut self, cols: Vec<&str>) -> Self {
        if let ExportSource::Table {
            columns: ref mut c, ..
        } = self.source
        {
            *c = cols.into_iter().map(String::from).collect();
        }
        self
    }

    /// Set the HTTP address for the export destination.
    ///
    /// The protocol (http:// or https://) will be determined automatically
    /// based on whether a public key is set.
    ///
    /// # Arguments
    ///
    /// * `addr` - The address in the format "host:port".
    pub fn at_address(mut self, addr: &str) -> Self {
        self.address = addr.to_string();
        self
    }

    /// Set the public key fingerprint for TLS encryption.
    ///
    /// When set, the export will use HTTPS and include a PUBLIC KEY clause.
    ///
    /// # Arguments
    ///
    /// * `fingerprint` - The SHA-256 fingerprint of the public key.
    pub fn with_public_key(mut self, fingerprint: &str) -> Self {
        self.public_key = Some(fingerprint.to_string());
        self
    }

    /// Set the output file name.
    ///
    /// Default is "001.csv". The compression extension will be appended automatically
    /// if compression is enabled.
    ///
    /// # Arguments
    ///
    /// * `name` - The file name.
    pub fn file_name(mut self, name: &str) -> Self {
        self.file_name = name.to_string();
        self
    }

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

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

    /// Set the row separator.
    ///
    /// Default is LF (Unix-style line endings).
    ///
    /// # Arguments
    ///
    /// * `sep` - The row separator.
    pub fn row_separator(mut self, sep: RowSeparator) -> Self {
        self.row_separator = sep;
        self
    }

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

    /// Set a custom NULL value representation.
    ///
    /// By default, NULL values are exported as empty strings.
    ///
    /// # Arguments
    ///
    /// * `val` - The string to use for NULL values.
    pub fn null_value(mut self, val: &str) -> Self {
        self.null_value = Some(val.to_string());
        self
    }

    /// Set the delimit mode.
    ///
    /// Default is Auto.
    ///
    /// # Arguments
    ///
    /// * `mode` - The delimit mode.
    pub fn delimit_mode(mut self, mode: DelimitMode) -> Self {
        self.delimit_mode = mode;
        self
    }

    /// Set the compression type.
    ///
    /// The appropriate file extension will be added automatically.
    ///
    /// # Arguments
    ///
    /// * `compression` - The compression type.
    pub fn compressed(mut self, compression: Compression) -> Self {
        self.compression = compression;
        self
    }

    /// Set whether to include column names in the output.
    ///
    /// Default is false.
    ///
    /// # Arguments
    ///
    /// * `include` - Whether to include column names.
    pub fn with_column_names(mut self, include: bool) -> Self {
        self.with_column_names = include;
        self
    }

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

        // Build the source part
        match &self.source {
            ExportSource::Table {
                schema,
                name,
                columns,
            } => {
                sql.push_str("EXPORT ");
                if let Some(s) = schema {
                    sql.push_str(s);
                    sql.push('.');
                }
                sql.push_str(name);
                if !columns.is_empty() {
                    sql.push_str(" (");
                    sql.push_str(&columns.join(", "));
                    sql.push(')');
                }
            }
            ExportSource::Query { sql: query } => {
                sql.push_str("EXPORT (");
                sql.push_str(query);
                sql.push(')');
            }
        }

        // Build the destination part
        sql.push_str("\nINTO CSV AT '");

        // Determine protocol based on public key
        if self.public_key.is_some() {
            sql.push_str("https://");
        } else {
            sql.push_str("http://");
        }
        sql.push_str(&self.address);
        sql.push('\'');

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

        // Add file name with compression extension
        sql.push_str("\nFILE '");
        sql.push_str(&self.file_name);
        sql.push_str(self.compression.extension());
        sql.push('\'');

        // Add format options
        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.as_sql());
        sql.push('\'');

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

        // Add WITH COLUMN NAMES if enabled
        if self.with_column_names {
            sql.push_str("\nWITH COLUMN NAMES");
        }

        // Add DELIMIT mode
        sql.push_str("\nDELIMIT = ");
        sql.push_str(self.delimit_mode.as_sql());

        sql
    }
}

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

    // Test basic export statement generation from table
    #[test]
    fn test_export_from_table_basic() {
        let sql = ExportQuery::from_table("users")
            .at_address("192.168.1.100:8080")
            .build();

        assert!(sql.starts_with("EXPORT users"));
        assert!(sql.contains("INTO CSV AT 'http://192.168.1.100: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'"));
        assert!(sql.contains("DELIMIT = AUTO"));
    }

    #[test]
    fn test_export_from_table_with_schema() {
        let sql = ExportQuery::from_table("users")
            .schema("my_schema")
            .at_address("192.168.1.100:8080")
            .build();

        assert!(sql.starts_with("EXPORT my_schema.users"));
    }

    #[test]
    fn test_export_from_table_with_columns() {
        let sql = ExportQuery::from_table("users")
            .columns(vec!["id", "name", "email"])
            .at_address("192.168.1.100:8080")
            .build();

        assert!(sql.starts_with("EXPORT users (id, name, email)"));
    }

    #[test]
    fn test_export_from_table_with_schema_and_columns() {
        let sql = ExportQuery::from_table("users")
            .schema("my_schema")
            .columns(vec!["id", "name"])
            .at_address("192.168.1.100:8080")
            .build();

        assert!(sql.starts_with("EXPORT my_schema.users (id, name)"));
    }

    // Test export from query
    #[test]
    fn test_export_from_query() {
        let sql = ExportQuery::from_query("SELECT * FROM users WHERE active = true")
            .at_address("192.168.1.100:8080")
            .build();

        assert!(sql.starts_with("EXPORT (SELECT * FROM users WHERE active = true)"));
        assert!(sql.contains("INTO CSV AT 'http://192.168.1.100:8080'"));
    }

    #[test]
    fn test_export_from_query_complex() {
        let sql = ExportQuery::from_query(
            "SELECT u.id, u.name, COUNT(o.id) FROM users u JOIN orders o ON u.id = o.user_id GROUP BY u.id, u.name",
        )
        .at_address("192.168.1.100:8080")
        .build();

        assert!(sql.contains("EXPORT (SELECT u.id, u.name, COUNT(o.id) FROM users u JOIN orders o ON u.id = o.user_id GROUP BY u.id, u.name)"));
    }

    // Test all format options
    #[test]
    fn test_export_with_all_format_options() {
        let sql = ExportQuery::from_table("data")
            .at_address("192.168.1.100:8080")
            .column_separator(';')
            .column_delimiter('\'')
            .row_separator(RowSeparator::CRLF)
            .encoding("ISO-8859-1")
            .null_value("NULL")
            .delimit_mode(DelimitMode::Always)
            .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("NULL = 'NULL'"));
        assert!(sql.contains("DELIMIT = ALWAYS"));
    }

    #[test]
    fn test_export_row_separator_cr() {
        let sql = ExportQuery::from_table("data")
            .at_address("192.168.1.100:8080")
            .row_separator(RowSeparator::CR)
            .build();

        assert!(sql.contains("ROW SEPARATOR = 'CR'"));
    }

    #[test]
    fn test_export_delimit_mode_never() {
        let sql = ExportQuery::from_table("data")
            .at_address("192.168.1.100:8080")
            .delimit_mode(DelimitMode::Never)
            .build();

        assert!(sql.contains("DELIMIT = NEVER"));
    }

    // Test with encryption (PUBLIC KEY)
    #[test]
    fn test_export_with_public_key() {
        let fingerprint = "AB:CD:EF:12:34:56:78:90:AB:CD:EF:12:34:56:78:90";
        let sql = ExportQuery::from_table("users")
            .at_address("192.168.1.100:8080")
            .with_public_key(fingerprint)
            .build();

        assert!(sql.contains("INTO CSV AT 'https://192.168.1.100:8080'"));
        assert!(sql.contains(&format!("PUBLIC KEY '{}'", fingerprint)));
    }

    #[test]
    fn test_export_without_public_key_uses_http() {
        let sql = ExportQuery::from_table("users")
            .at_address("192.168.1.100:8080")
            .build();

        assert!(sql.contains("INTO CSV AT 'http://192.168.1.100:8080'"));
        assert!(!sql.contains("PUBLIC KEY"));
    }

    // Test WITH COLUMN NAMES
    #[test]
    fn test_export_with_column_names() {
        let sql = ExportQuery::from_table("users")
            .at_address("192.168.1.100:8080")
            .with_column_names(true)
            .build();

        assert!(sql.contains("WITH COLUMN NAMES"));
    }

    #[test]
    fn test_export_without_column_names() {
        let sql = ExportQuery::from_table("users")
            .at_address("192.168.1.100:8080")
            .with_column_names(false)
            .build();

        assert!(!sql.contains("WITH COLUMN NAMES"));
    }

    // Test compression file extensions
    #[test]
    fn test_export_no_compression() {
        let sql = ExportQuery::from_table("users")
            .at_address("192.168.1.100:8080")
            .compressed(Compression::None)
            .build();

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

    #[test]
    fn test_export_gzip_compression() {
        let sql = ExportQuery::from_table("users")
            .at_address("192.168.1.100:8080")
            .compressed(Compression::Gzip)
            .build();

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

    #[test]
    fn test_export_bzip2_compression() {
        let sql = ExportQuery::from_table("users")
            .at_address("192.168.1.100:8080")
            .compressed(Compression::Bzip2)
            .build();

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

    #[test]
    fn test_export_custom_file_name_with_compression() {
        let sql = ExportQuery::from_table("users")
            .at_address("192.168.1.100:8080")
            .file_name("export_data.csv")
            .compressed(Compression::Gzip)
            .build();

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

    // Test complete export statement
    #[test]
    fn test_export_complete_statement() {
        let sql = ExportQuery::from_table("orders")
            .schema("sales")
            .columns(vec!["order_id", "customer_id", "total"])
            .at_address("10.0.0.1:3000")
            .with_public_key("SHA256:fingerprint123")
            .file_name("orders_export.csv")
            .column_separator('|')
            .column_delimiter('"')
            .row_separator(RowSeparator::LF)
            .encoding("UTF-8")
            .null_value("\\N")
            .with_column_names(true)
            .delimit_mode(DelimitMode::Always)
            .compressed(Compression::Gzip)
            .build();

        // Verify all parts of the statement
        assert!(sql.starts_with("EXPORT sales.orders (order_id, customer_id, total)"));
        assert!(sql.contains("INTO CSV AT 'https://10.0.0.1:3000'"));
        assert!(sql.contains("PUBLIC KEY 'SHA256:fingerprint123'"));
        assert!(sql.contains("FILE 'orders_export.csv.gz'"));
        assert!(sql.contains("ENCODING = 'UTF-8'"));
        assert!(sql.contains("COLUMN SEPARATOR = '|'"));
        assert!(sql.contains("COLUMN DELIMITER = '\"'"));
        assert!(sql.contains("ROW SEPARATOR = 'LF'"));
        assert!(sql.contains("NULL = '\\N'"));
        assert!(sql.contains("WITH COLUMN NAMES"));
        assert!(sql.contains("DELIMIT = ALWAYS"));
    }

    // Test enum helper methods
    #[test]
    fn test_row_separator_as_sql() {
        assert_eq!(RowSeparator::LF.as_sql(), "LF");
        assert_eq!(RowSeparator::CR.as_sql(), "CR");
        assert_eq!(RowSeparator::CRLF.as_sql(), "CRLF");
    }

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

    #[test]
    fn test_delimit_mode_as_sql() {
        assert_eq!(DelimitMode::Auto.as_sql(), "AUTO");
        assert_eq!(DelimitMode::Always.as_sql(), "ALWAYS");
        assert_eq!(DelimitMode::Never.as_sql(), "NEVER");
    }

    // Test default values
    #[test]
    fn test_default_values() {
        assert_eq!(RowSeparator::default(), RowSeparator::LF);
        assert_eq!(Compression::default(), Compression::None);
        assert_eq!(DelimitMode::default(), DelimitMode::Auto);
    }

    // Test that schema/columns methods are no-op for query source
    #[test]
    fn test_schema_columns_ignored_for_query() {
        let sql = ExportQuery::from_query("SELECT 1")
            .schema("ignored_schema")
            .columns(vec!["ignored_col"])
            .at_address("192.168.1.100:8080")
            .build();

        assert!(sql.starts_with("EXPORT (SELECT 1)"));
        assert!(!sql.contains("ignored_schema"));
        assert!(!sql.contains("ignored_col"));
    }
}