tinyetl 0.3.0

Fast, zero-config ETL in a single binary for transforming data between formats and databases
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
use std::collections::HashMap;
use async_trait::async_trait;
use tiberius::{Client, Config, AuthMethod, QueryItem};
use tokio::net::TcpStream;
use tokio_util::compat::TokioAsyncWriteCompatExt;
use futures_util::stream::TryStreamExt;
use url::Url;
use rust_decimal::Decimal;
use rust_decimal::prelude::ToPrimitive;
use chrono::{DateTime, Utc, NaiveDate, NaiveDateTime};
use uuid::Uuid;

use crate::{
    Result, TinyEtlError,
    schema::{Schema, Row, Value, Column, DataType, SchemaInferer},
    connectors::{Source, Target},
};

type MssqlClient = Client<tokio_util::compat::Compat<TcpStream>>;

pub struct MssqlSource {
    connection_string: String,
    client: Option<MssqlClient>,
    table_name: String,
    query: Option<String>,
    current_offset: usize,
    total_rows: Option<usize>,
    schema: Option<Schema>,
}

impl MssqlSource {
    pub fn new(connection_string: &str) -> Result<Self> {
        let (_, table) = Self::parse_connection_string(connection_string)?;
        
        Ok(Self {
            connection_string: connection_string.to_string(),
            client: None,
            table_name: table,
            query: None,
            current_offset: 0,
            total_rows: None,
            schema: None,
        })
    }

    pub fn with_query(mut self, query: String) -> Self {
        self.query = Some(query);
        self
    }

    fn parse_connection_string(connection_string: &str) -> Result<(String, String)> {
        if let Some((db_part, table_part)) = connection_string.split_once('#') {
            Ok((db_part.to_string(), table_part.to_string()))
        } else {
            Err(TinyEtlError::Configuration(
                "MSSQL connection string must include table name: connection_string#table_name".to_string()
            ))
        }
    }

    async fn create_client(connection_string: &str) -> Result<MssqlClient> {
        let url = Url::parse(connection_string).map_err(|e| {
            TinyEtlError::Configuration(format!("Invalid MSSQL URL: {}", e))
        })?;

        let mut config = Config::new();
        
        // Set server address
        if let Some(host) = url.host_str() {
            config.host(host);
        }
        
        // Set port
        if let Some(port) = url.port() {
            config.port(port);
        } else {
            config.port(1433); // Default MSSQL port
        }
        
        // Set database name
        let database = url.path().trim_start_matches('/');
        if !database.is_empty() {
            config.database(database);
        }

        // Set authentication
        if !url.username().is_empty() {
            let username = url.username();
            let password = url.password().unwrap_or("");
            config.authentication(AuthMethod::sql_server(username, password));
        } else {
            // For simplicity, we require username/password authentication
            return Err(TinyEtlError::Configuration(
                "MSSQL connection requires username and password in URL format: mssql://user:pass@host:port/database#table".to_string()
            ));
        }

        // Trust server certificate (for development)
        config.trust_cert();

        let tcp = TcpStream::connect(config.get_addr())
            .await
            .map_err(|e| TinyEtlError::Connection(format!("Failed to connect to MSSQL server: {}", e)))?;

        let client = Client::connect(config, tcp.compat_write())
            .await
            .map_err(|e| TinyEtlError::Connection(format!("Failed to authenticate with MSSQL: {}", e)))?;

        Ok(client)
    }
}

#[async_trait]
impl Source for MssqlSource {
    async fn connect(&mut self) -> Result<()> {
        let (db_part, _) = Self::parse_connection_string(&self.connection_string)?;
        self.client = Some(Self::create_client(&db_part).await?);
        Ok(())
    }

    async fn infer_schema(&mut self, _sample_size: usize) -> Result<Schema> {
        if self.client.is_none() {
            self.connect().await?;
        }

        let client = self.client.as_mut().unwrap();
        
        // Get column information from the table
        let query = format!(
            "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{}' ORDER BY ORDINAL_POSITION",
            self.table_name
        );

        let mut stream = client.query(query, &[])
            .await
            .map_err(|e| TinyEtlError::SchemaInference(format!("Failed to get table schema: {}", e)))?;

        let mut columns = Vec::new();

        while let Some(item) = stream.try_next().await
            .map_err(|e| TinyEtlError::SchemaInference(format!("Failed to fetch schema results: {}", e)))? {
            
            if let tiberius::QueryItem::Row(row) = item {
                let column_name: &str = row.get(0).ok_or_else(|| {
                    TinyEtlError::SchemaInference("Missing column name".to_string())
                })?;
                let data_type: &str = row.get(1).ok_or_else(|| {
                    TinyEtlError::SchemaInference("Missing data type".to_string())
                })?;
                let is_nullable: &str = row.get(2).ok_or_else(|| {
                    TinyEtlError::SchemaInference("Missing nullable info".to_string())
                })?;

            let data_type = match data_type.to_uppercase().as_str() {
                "INT" | "SMALLINT" | "TINYINT" | "BIGINT" => DataType::Integer,
                "FLOAT" | "REAL" | "DECIMAL" | "NUMERIC" | "MONEY" | "SMALLMONEY" => DataType::Decimal,
                "VARCHAR" | "NVARCHAR" | "CHAR" | "NCHAR" | "TEXT" | "NTEXT" => DataType::String,
                "BIT" => DataType::Boolean,
                "DATE" => DataType::Date,
                "DATETIME" | "DATETIME2" | "SMALLDATETIME" | "TIMESTAMP" => DataType::DateTime,
                "UNIQUEIDENTIFIER" => DataType::String,
                _ => DataType::String,
            };

            columns.push(Column {
                name: column_name.to_string(),
                data_type,
                nullable: is_nullable.eq_ignore_ascii_case("YES"),
            });
            }
        }

        if columns.is_empty() {
            return Err(TinyEtlError::SchemaInference(format!(
                "Table '{}' not found or has no columns", self.table_name
            )));
        }

        let schema = Schema { 
            columns,
            estimated_rows: None,
            primary_key_candidate: None,
        };
        
        self.schema = Some(schema.clone());
        Ok(schema)
    }

    async fn read_batch(&mut self, batch_size: usize) -> Result<Vec<Row>> {
        if self.client.is_none() {
            return Err(TinyEtlError::Connection("Not connected to MSSQL".to_string()));
        }

        // Ensure we have schema
        if self.schema.is_none() {
            self.infer_schema(1000).await?;
        }

        let client = self.client.as_mut().unwrap();
        let schema = self.schema.as_ref().unwrap();
        
        let query = if let Some(ref custom_query) = self.query {
            format!("{} ORDER BY (SELECT NULL) OFFSET {} ROWS FETCH NEXT {} ROWS ONLY", 
                    custom_query, self.current_offset, batch_size)
        } else {
            format!("SELECT * FROM {} ORDER BY (SELECT NULL) OFFSET {} ROWS FETCH NEXT {} ROWS ONLY", 
                    self.table_name, self.current_offset, batch_size)
        };

        let mut stream = client.query(query, &[])
            .await
            .map_err(|e| TinyEtlError::DataTransfer(format!("Failed to execute query: {}", e)))?;

        let mut rows = Vec::new();

        while let Some(item) = stream.try_next().await
            .map_err(|e| TinyEtlError::DataTransfer(format!("Failed to fetch results: {}", e)))? {
            
            if let tiberius::QueryItem::Row(row) = item {
                let mut row_data = HashMap::new();
                for (i, column) in schema.columns.iter().enumerate() {
                    let value = match row.try_get::<&str, usize>(i) {
                        Ok(Some(s)) => Value::String(s.to_string()),
                        Ok(None) => Value::Null,
                        Err(_) => {
                            // Try different types
                            if let Ok(Some(v)) = row.try_get::<i64, usize>(i) {
                                Value::Integer(v)
                            } else if let Ok(Some(v)) = row.try_get::<f64, usize>(i) {
                                Value::Decimal(Decimal::from_f64_retain(v).unwrap_or_default())
                            } else if let Ok(Some(v)) = row.try_get::<bool, usize>(i) {
                                Value::Boolean(v)
                            } else if let Ok(Some(v)) = row.try_get::<NaiveDateTime, usize>(i) {
                                // Convert NaiveDateTime to DateTime<Utc>
                                Value::Date(DateTime::from_utc(v, Utc))
                            } else {
                                Value::Null
                            }
                        }
                    };
                    row_data.insert(column.name.clone(), value);
                }
                rows.push(row_data);
            }
        }        self.current_offset += rows.len();
        Ok(rows)
    }

    async fn estimated_row_count(&self) -> Result<Option<usize>> {
        if self.total_rows.is_some() {
            return Ok(self.total_rows);
        }

        Ok(None) // For simplicity, we don't implement this optimization
    }

    async fn reset(&mut self) -> Result<()> {
        self.current_offset = 0;
        Ok(())
    }

    fn has_more(&self) -> bool {
        // This is a simple heuristic - in a real implementation, you might want to
        // track this more precisely
        true
    }
}

pub struct MssqlTarget {
    connection_string: String,
    table_name: String,
    client: Option<MssqlClient>,
    max_batch_size: usize,
    schema: Option<Schema>,
}

impl MssqlTarget {
    pub fn new(connection_string: &str) -> Result<Self> {
        let (_, table_name) = Self::parse_connection_string(connection_string)?;
        
        Ok(Self {
            connection_string: connection_string.to_string(),
            table_name,
            client: None,
            max_batch_size: 1000,
            schema: None,
        })
    }

    pub fn with_batch_size(mut self, batch_size: usize) -> Self {
        self.max_batch_size = batch_size.max(1);
        self
    }

    fn parse_connection_string(connection_string: &str) -> Result<(String, String)> {
        if let Some((db_part, table_part)) = connection_string.split_once('#') {
            Ok((db_part.to_string(), table_part.to_string()))
        } else {
            Err(TinyEtlError::Configuration(
                "MSSQL connection string must include table name: connection_string#table_name".to_string()
            ))
        }
    }

    async fn create_client(connection_string: &str) -> Result<MssqlClient> {
        MssqlSource::create_client(connection_string).await
    }

    fn sql_type_from_data_type(data_type: &DataType) -> &'static str {
        match data_type {
            DataType::Integer => "BIGINT",
            DataType::Decimal => "DECIMAL(18,6)",
            DataType::String => "NVARCHAR(MAX)",
            DataType::Boolean => "BIT",
            DataType::Date => "DATE",
            DataType::DateTime => "DATETIME2",
            DataType::Null => "NVARCHAR(MAX)", // Default to string for null type
        }
    }

    fn format_value_for_insert(value: &Value, expected_type: &DataType) -> String {
        match value {
            Value::Null => "NULL".to_string(),
            Value::String(s) => {
                // Try to coerce string to expected type
                match expected_type {
                    DataType::Integer => {
                        if let Ok(i) = s.parse::<i64>() {
                            i.to_string()
                        } else {
                            "NULL".to_string()
                        }
                    }
                    DataType::Decimal => {
                        if let Ok(d) = s.parse::<f64>() {
                            d.to_string()
                        } else {
                            "NULL".to_string()
                        }
                    }
                    DataType::Boolean => {
                        match s.to_lowercase().as_str() {
                            "true" | "1" | "yes" => "1".to_string(),
                            "false" | "0" | "no" => "0".to_string(),
                            _ => "NULL".to_string(),
                        }
                    }
                    _ => format!("N'{}'", s.replace("'", "''")),
                }
            }
            Value::Integer(i) => {
                match expected_type {
                    DataType::String => format!("N'{}'", i),
                    _ => i.to_string(),
                }
            }
            Value::Decimal(d) => {
                match expected_type {
                    DataType::String => {
                        if let Some(f) = d.to_f64() {
                            format!("N'{}'", f)
                        } else {
                            "NULL".to_string()
                        }
                    }
                    _ => {
                        if let Some(f) = d.to_f64() {
                            f.to_string()
                        } else {
                            "NULL".to_string()
                        }
                    }
                }
            }
            Value::Boolean(b) => {
                match expected_type {
                    DataType::String => format!("N'{}'", if *b { "true" } else { "false" }),
                    _ => if *b { "1" } else { "0" }.to_string(),
                }
            }
            Value::Date(dt) => format!("'{}'", dt.format("%Y-%m-%d %H:%M:%S%.3f")),
        }
    }

    // Write value directly to a string buffer for better performance
    fn write_value_to_buffer(buffer: &mut String, value: &Value, expected_type: &DataType) {
        match value {
            Value::Null => buffer.push_str("NULL"),
            Value::String(s) => {
                match expected_type {
                    DataType::Integer => {
                        if let Ok(i) = s.parse::<i64>() {
                            buffer.push_str(&i.to_string());
                        } else {
                            buffer.push_str("NULL");
                        }
                    }
                    DataType::Decimal => {
                        if let Ok(d) = s.parse::<f64>() {
                            buffer.push_str(&d.to_string());
                        } else {
                            buffer.push_str("NULL");
                        }
                    }
                    DataType::Boolean => {
                        buffer.push_str(match s.to_lowercase().as_str() {
                            "true" | "1" | "yes" => "1",
                            "false" | "0" | "no" => "0",
                            _ => "NULL",
                        });
                    }
                    _ => {
                        buffer.push_str("N'");
                        // Escape single quotes
                        for ch in s.chars() {
                            if ch == '\'' {
                                buffer.push_str("''");
                            } else {
                                buffer.push(ch);
                            }
                        }
                        buffer.push('\'');
                    }
                }
            }
            Value::Integer(i) => {
                if matches!(expected_type, DataType::String) {
                    buffer.push_str("N'");
                    buffer.push_str(&i.to_string());
                    buffer.push('\'');
                } else {
                    buffer.push_str(&i.to_string());
                }
            }
            Value::Decimal(d) => {
                if let Some(f) = d.to_f64() {
                    if matches!(expected_type, DataType::String) {
                        buffer.push_str("N'");
                        buffer.push_str(&f.to_string());
                        buffer.push('\'');
                    } else {
                        buffer.push_str(&f.to_string());
                    }
                } else {
                    buffer.push_str("NULL");
                }
            }
            Value::Boolean(b) => {
                if matches!(expected_type, DataType::String) {
                    buffer.push_str(if *b { "N'true'" } else { "N'false'" });
                } else {
                    buffer.push(if *b { '1' } else { '0' });
                }
            }
            Value::Date(dt) => {
                buffer.push('\'');
                buffer.push_str(&dt.format("%Y-%m-%d %H:%M:%S%.3f").to_string());
                buffer.push('\'');
            }
        }
    }
}

#[async_trait]
impl Target for MssqlTarget {
    async fn connect(&mut self) -> Result<()> {
        let (db_part, _) = Self::parse_connection_string(&self.connection_string)?;
        self.client = Some(Self::create_client(&db_part).await?);
        Ok(())
    }

    async fn create_table(&mut self, table_name: &str, schema: &Schema) -> Result<()> {
        if self.client.is_none() {
            self.connect().await?;
        }

        let client = self.client.as_mut().unwrap();
        self.schema = Some(schema.clone());

        // Build CREATE TABLE statement with IF NOT EXISTS logic
        let mut columns_sql = Vec::new();
        for column in &schema.columns {
            let sql_type = Self::sql_type_from_data_type(&column.data_type);
            let nullable = if column.nullable { "NULL" } else { "NOT NULL" };
            columns_sql.push(format!("[{}] {} {}", column.name, sql_type, nullable));
        }

        // SQL Server doesn't have CREATE TABLE IF NOT EXISTS, so we use IF NOT EXISTS wrapper
        let create_table_sql = format!(
            "IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{}') \
             BEGIN CREATE TABLE [{}] ({}) END",
            table_name.replace("'", "''"), // Escape single quotes
            table_name,
            columns_sql.join(", ")
        );

        client.execute(&create_table_sql, &[])
            .await
            .map_err(|e| TinyEtlError::DataTransfer(format!("Failed to create table: {}", e)))?;

        Ok(())
    }

    async fn write_batch(&mut self, rows: &[Row]) -> Result<usize> {
        if self.client.is_none() {
            return Err(TinyEtlError::Connection("Not connected to MSSQL".to_string()));
        }

        if rows.is_empty() {
            return Ok(0);
        }

        let client = self.client.as_mut().unwrap();
        let schema = self.schema.as_ref()
            .ok_or_else(|| TinyEtlError::DataTransfer("Schema not set".to_string()))?;

        // Build column names
        let column_names: Vec<String> = schema.columns.iter()
            .map(|c| format!("[{}]", c.name))
            .collect();

        let mut total_written = 0;
        
        // Process rows in larger chunks for better performance
        // SQL Server can handle 1000 rows per INSERT statement efficiently
        let chunk_size = self.max_batch_size.min(1000);
        
        for chunk in rows.chunks(chunk_size) {
            // Build the INSERT statement directly to avoid intermediate allocations
            // Estimate size: table name + columns + (~100 bytes per row avg)
            let estimated_size = 200 + column_names.len() * 25 + chunk.len() * 150;
            let mut insert_sql = String::with_capacity(estimated_size);
            
            insert_sql.push_str("INSERT INTO [");
            insert_sql.push_str(&self.table_name);
            insert_sql.push_str("] (");
            insert_sql.push_str(&column_names.join(", "));
            insert_sql.push_str(") VALUES ");
            
            for (row_idx, row) in chunk.iter().enumerate() {
                if row.len() != schema.columns.len() {
                    return Err(TinyEtlError::DataTransfer(format!(
                        "Row has {} values but schema expects {}",
                        row.len(),
                        schema.columns.len()
                    )));
                }

                if row_idx > 0 {
                    insert_sql.push_str(", ");
                }
                insert_sql.push('(');
                
                // Write VALUES clause directly into the string buffer for maximum performance
                for (col_idx, col) in schema.columns.iter().enumerate() {
                    if col_idx > 0 {
                        insert_sql.push_str(", ");
                    }
                    
                    let value = row.get(&col.name).unwrap_or(&Value::Null);
                    Self::write_value_to_buffer(&mut insert_sql, value, &col.data_type);
                }
                
                insert_sql.push(')');
            }

            client.execute(&insert_sql, &[]).await
                .map_err(|e| TinyEtlError::DataTransfer(format!("Failed to insert batch: {}", e)))?;

            total_written += chunk.len();
        }

        Ok(total_written)
    }

    async fn finalize(&mut self) -> Result<()> {
        // MSSQL doesn't require explicit finalization for basic operations
        Ok(())
    }

    async fn exists(&self, table_name: &str) -> Result<bool> {
        if self.client.is_none() {
            return Err(TinyEtlError::Connection("Not connected to MSSQL".to_string()));
        }

        // We need to create a temporary connection since the method is not mutable
        let (db_part, _) = Self::parse_connection_string(&self.connection_string)?;
        let mut client = Self::create_client(&db_part).await?;
        
        let query = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @P1";
        let mut stream = client.query(query, &[&table_name])
            .await
            .map_err(|e| TinyEtlError::Connection(format!("Failed to check table existence: {}", e)))?;

        if let Some(item) = stream.try_next().await
            .map_err(|e| TinyEtlError::Connection(format!("Failed to fetch existence result: {}", e)))? {
            
            if let tiberius::QueryItem::Row(row) = item {
                if let Ok(Some(count)) = row.try_get::<i32, usize>(0) {
                    return Ok(count > 0);
                }
            }
        }

        Ok(false)
    }

    async fn truncate(&mut self, table_name: &str) -> Result<()> {
        if self.client.is_none() {
            self.connect().await?;
        }

        let client = self.client.as_mut().unwrap();
        let truncate_sql = format!("TRUNCATE TABLE [{}]", table_name);

        client.execute(&truncate_sql, &[])
            .await
            .map_err(|e| TinyEtlError::DataTransfer(format!("Failed to truncate table: {}", e)))?;

        Ok(())
    }

    fn supports_append(&self) -> bool {
        true // MSSQL supports INSERT operations on existing tables
    }
}