tinyetl 0.11.1

Fast, zero-config ETL in a single binary for transforming data between formats and databases
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
mod arrow_values;
pub mod avro;
pub mod csv;
pub mod duckdb;
pub mod excel;
pub mod json;
pub mod mssql;
pub mod mysql;
pub mod odbc;
mod output_file;
pub mod parquet;
pub mod postgres;
mod row_stream;
pub mod snowflake;
pub mod sqlite;

use crate::{
    schema::{Row, Schema},
    Result,
};
use async_trait::async_trait;

#[async_trait]
pub trait Source: Send + Sync {
    /// Connect to the source and validate it's accessible
    async fn connect(&mut self) -> Result<()>;

    /// Infer schema by reading a sample of data
    async fn infer_schema(&mut self, sample_size: usize) -> Result<Schema>;

    /// Read data in batches
    async fn read_batch(&mut self, batch_size: usize) -> Result<Vec<Row>>;

    /// Get estimated total row count if available
    async fn estimated_row_count(&self) -> Result<Option<usize>>;

    /// Reset to beginning for re-reading
    async fn reset(&mut self) -> Result<()>;

    /// Check if there's more data to read
    fn has_more(&self) -> bool;
}

#[async_trait]
pub trait Target: Send + Sync {
    /// Connect to the target and validate it's accessible
    async fn connect(&mut self) -> Result<()>;

    /// Create the target table/structure based on schema
    async fn create_table(&mut self, table_name: &str, schema: &Schema) -> Result<()>;

    /// Write a batch of rows
    async fn write_batch(&mut self, rows: &[Row]) -> Result<usize>;

    /// Finalize the write operation
    async fn finalize(&mut self) -> Result<()>;

    /// Check if target already exists
    async fn exists(&self, table_name: &str) -> Result<bool>;

    /// Truncate the target (remove all existing data)
    /// This should be called before writing if truncate mode is enabled
    async fn truncate(&mut self, table_name: &str) -> Result<()>;

    /// Check if the target supports appending data
    /// Returns true if data can be appended to existing target, false if it requires truncation
    fn supports_append(&self) -> bool;
}

/// Factory function to create a source connector from a connection string
/// For new protocol-based connections (snowflake://, etc.), use create_source_from_url instead
pub fn create_source(connection_string: &str) -> Result<Box<dyn Source>> {
    if connection_string.ends_with(".csv") {
        Ok(Box::new(csv::CsvSource::new(connection_string)?))
    } else if connection_string.ends_with(".json") || json::is_json_lines(connection_string) {
        Ok(Box::new(json::JsonSource::new(connection_string)?))
    } else if connection_string.ends_with(".parquet") {
        Ok(Box::new(parquet::ParquetSource::new(connection_string)?))
    } else if connection_string.ends_with(".avro") {
        Ok(Box::new(avro::AvroSource::new(connection_string)?))
    } else if excel::is_spreadsheet(connection_string) {
        Ok(Box::new(excel::ExcelSource::new(connection_string)?))
    } else if (connection_string.contains(".duckdb#") || connection_string.ends_with(".duckdb"))
        || connection_string.starts_with("duckdb:")
    {
        Ok(Box::new(duckdb::DuckdbSource::new(connection_string)?))
    } else if (connection_string.contains(".db#") || connection_string.ends_with(".db"))
        || connection_string.starts_with("sqlite:")
    {
        Ok(Box::new(sqlite::SqliteSource::new(connection_string)?))
    } else if connection_string.starts_with("postgres://")
        || connection_string.starts_with("postgresql://")
    {
        Ok(Box::new(postgres::PostgresSource::new(connection_string)?))
    } else if connection_string.starts_with("mysql://") {
        Ok(Box::new(mysql::MysqlSource::new(connection_string)?))
    } else if connection_string.starts_with("mssql://")
        || connection_string.starts_with("sqlserver://")
    {
        Ok(Box::new(mssql::MssqlSource::new(connection_string)?))
    } else if connection_string.starts_with("odbc://") {
        Ok(Box::new(odbc::OdbcSource::new(connection_string)?))
    } else if connection_string.starts_with("snowflake://") {
        Ok(Box::new(snowflake::SnowflakeSource::new(
            connection_string,
            &std::collections::HashMap::new(),
        )?))
    } else {
        Err(crate::TinyEtlError::Configuration(
            format!("Unsupported source type: {}. Supported formats: file.csv, file.json, file.jsonl, file.parquet, file.avro, file.xlsx[#sheet] (also .xlsm, .xlsb, .xls, .ods), file.db#table, file.duckdb#table, postgres://user:pass@host:port/db#table, mysql://user:pass@host:port/db#table, mssql://user:pass@host:port/db#table, odbc://connection_string#table, snowflake://user@account/db/schema#table", connection_string)
        ))
    }
}

/// Factory function to create a target connector from a connection string
/// Supports both protocol-based and legacy file-based connections
pub fn create_target(connection_string: &str) -> Result<Box<dyn Target>> {
    // Handle protocol-based connections first
    if connection_string.contains("://") {
        if connection_string.starts_with("duckdb://") {
            return Ok(Box::new(duckdb::DuckdbTarget::new(connection_string)?));
        } else if connection_string.starts_with("sqlite://") {
            return Ok(Box::new(sqlite::SqliteTarget::new(connection_string)?));
        } else if connection_string.starts_with("postgres://")
            || connection_string.starts_with("postgresql://")
        {
            return Ok(Box::new(postgres::PostgresTarget::new(connection_string)?));
        } else if connection_string.starts_with("mysql://") {
            return Ok(Box::new(mysql::MysqlTarget::new(connection_string)?));
        } else if connection_string.starts_with("mssql://")
            || connection_string.starts_with("sqlserver://")
        {
            return Ok(Box::new(mssql::MssqlTarget::new(connection_string)?));
        } else if connection_string.starts_with("odbc://") {
            return Ok(Box::new(odbc::OdbcTarget::new(connection_string)?));
        } else if connection_string.starts_with("snowflake://") {
            return Ok(Box::new(snowflake::SnowflakeTarget::new(
                connection_string,
                &std::collections::HashMap::new(),
            )?));
        } else {
            return Err(crate::TinyEtlError::Configuration(format!(
                "Unsupported protocol in: {}. Supported protocols: duckdb://, sqlite://, postgres://, mysql://, mssql://, odbc://, snowflake://",
                connection_string
            )));
        }
    }

    // Handle legacy file-based and non-protocol database connections
    if connection_string.ends_with(".csv") {
        Ok(Box::new(csv::CsvTarget::new(connection_string)?))
    } else if connection_string.ends_with(".json") || json::is_json_lines(connection_string) {
        Ok(Box::new(json::JsonTarget::new(connection_string)?))
    } else if connection_string.ends_with(".parquet") {
        Ok(Box::new(parquet::ParquetTarget::new(connection_string)?))
    } else if connection_string.ends_with(".avro") {
        Ok(Box::new(avro::AvroTarget::new(connection_string)?))
    } else if excel::is_spreadsheet(connection_string) {
        Ok(Box::new(excel::ExcelTarget::new(connection_string)?))
    } else if connection_string.contains(".duckdb#")
        || connection_string.ends_with(".duckdb")
        || connection_string.starts_with("duckdb:")
    {
        // Legacy DuckDB support: file.duckdb, file.duckdb#table, duckdb:file.duckdb
        Ok(Box::new(duckdb::DuckdbTarget::new(connection_string)?))
    } else if connection_string.contains(".db#")
        || connection_string.ends_with(".db")
        || connection_string.starts_with("sqlite:")
    {
        // Legacy SQLite support: file.db, file.db#table, sqlite:file.db
        Ok(Box::new(sqlite::SqliteTarget::new(connection_string)?))
    } else {
        Err(crate::TinyEtlError::Configuration(format!(
            "Unsupported target type: {}. Supported formats: \
            file.csv, file.json, file.jsonl, file.parquet, file.avro, file.xlsx[#sheet], file.db, file.db#table, file.duckdb, file.duckdb#table, \
            duckdb://path/file.duckdb#table, sqlite://path/file.db#table, postgres://user:pass@host:port/db#table, mysql://user:pass@host:port/db#table, mssql://user:pass@host:port/db#table, odbc://connection_string#table, snowflake://user@account/db/schema#table",
            connection_string
        )))
    }
}

/// New protocol-aware factory functions that handle modern connection strings
/// Use these for new protocol support (snowflake://, onelake://, etc.)
/// Create a source using the new protocol abstraction
pub async fn create_source_from_url(connection_string: &str) -> Result<Box<dyn Source>> {
    create_source_from_url_with_type_and_options(
        connection_string,
        None,
        &std::collections::HashMap::new(),
    )
    .await
}

/// Create a source using the new protocol abstraction with optional type hint
pub async fn create_source_from_url_with_type(
    connection_string: &str,
    source_type: Option<&str>,
) -> Result<Box<dyn Source>> {
    create_source_from_url_with_type_and_options(
        connection_string,
        source_type,
        &std::collections::HashMap::new(),
    )
    .await
}

/// Create a source using the new protocol abstraction with optional type hint and options
pub async fn create_source_from_url_with_type_and_options(
    connection_string: &str,
    source_type: Option<&str>,
    options: &std::collections::HashMap<String, String>,
) -> Result<Box<dyn Source>> {
    // Snowflake is a database, but unlike the others it takes endpoint options (key path, ...)
    if connection_string.starts_with("snowflake://") {
        return Ok(Box::new(snowflake::SnowflakeSource::new(
            connection_string,
            options,
        )?));
    }
    // Check if this looks like a protocol URL
    if connection_string.contains("://") {
        // Try database connectors first for database protocols
        if connection_string.starts_with("duckdb://")
            || connection_string.starts_with("sqlite://")
            || connection_string.starts_with("postgres://")
            || connection_string.starts_with("postgresql://")
            || connection_string.starts_with("mysql://")
            || connection_string.starts_with("mssql://")
            || connection_string.starts_with("sqlserver://")
            || connection_string.starts_with("odbc://")
        {
            // Database connectors don't support protocol options yet
            create_source(connection_string)
        } else {
            // Fall back to protocol abstraction for other protocols (file://, snowflake://, etc.)
            crate::protocols::create_source_from_url_with_type(
                connection_string,
                source_type,
                options,
            )
            .await
        }
    } else {
        // Fallback to legacy connector system for backward compatibility
        create_source(connection_string)
    }
}

/// Create a target using the new protocol abstraction
pub async fn create_target_from_url(connection_string: &str) -> Result<Box<dyn Target>> {
    create_target_from_url_with_options(connection_string, &std::collections::HashMap::new()).await
}

/// Create a target using the new protocol abstraction with options
pub async fn create_target_from_url_with_options(
    connection_string: &str,
    options: &std::collections::HashMap<String, String>,
) -> Result<Box<dyn Target>> {
    if connection_string.starts_with("snowflake://") {
        return Ok(Box::new(snowflake::SnowflakeTarget::new(
            connection_string,
            options,
        )?));
    }
    // Check if this looks like a protocol URL
    if connection_string.contains("://") {
        // Try database connectors first for database protocols
        if connection_string.starts_with("sqlite://")
            || connection_string.starts_with("postgres://")
            || connection_string.starts_with("postgresql://")
            || connection_string.starts_with("mysql://")
            || connection_string.starts_with("mssql://")
            || connection_string.starts_with("sqlserver://")
            || connection_string.starts_with("odbc://")
        {
            // Database connectors don't support protocol options yet
            create_target(connection_string)
        } else {
            // Fall back to protocol abstraction for other protocols (file://, snowflake://, etc.)
            crate::protocols::create_target_from_url_with_options(connection_string, options).await
        }
    } else {
        // Fallback to legacy connector system for backward compatibility
        create_target(connection_string)
    }
}

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

    #[test]
    fn test_create_csv_source() {
        let source = create_source("test.csv");
        assert!(source.is_ok());
    }

    #[test]
    fn test_create_json_source() {
        let source = create_source("test.json");
        assert!(source.is_ok());
    }

    #[test]
    fn test_create_parquet_source() {
        let source = create_source("test.parquet");
        assert!(source.is_ok());
    }

    #[test]
    fn test_create_sqlite_source() {
        let result = create_source("test.db#table");
        if let Err(ref e) = result {
            println!("SQLite source creation failed: {}", e);
        }
        assert!(result.is_ok());
    }

    #[test]
    fn test_create_sqlite_source_without_table() {
        let result = create_source("test.db");
        assert!(result.is_err());
        if let Err(err) = result {
            // The error will come from the SQLite constructor, not the factory
            assert!(err
                .to_string()
                .contains("SQLite source requires table specification"));
        }
    }

    #[test]
    fn test_create_sqlite_with_sqlite_prefix() {
        let source = create_source("sqlite:test.db#table");
        assert!(source.is_ok());
    }

    #[test]
    fn test_create_postgres_source() {
        let source = create_source("postgres://user:pass@localhost:5432/db#table");
        assert!(source.is_ok());
    }

    #[test]
    fn test_create_postgres_source_without_table() {
        let result = create_source("postgres://user:pass@localhost:5432/db");
        assert!(result.is_err());
    }

    #[test]
    fn test_create_postgresql_source() {
        let source = create_source("postgresql://user:pass@localhost:5432/db#table");
        assert!(source.is_ok());
    }

    #[test]
    fn test_create_unsupported_source() {
        let source = create_source("test.unsupported");
        assert!(source.is_err());
    }

    #[test]
    fn test_create_csv_target() {
        let target = create_target("output.csv");
        assert!(target.is_ok());
    }

    #[test]
    fn test_create_json_target() {
        let target = create_target("output.json");
        assert!(target.is_ok());
    }

    #[test]
    fn test_create_parquet_target() {
        let target = create_target("output.parquet");
        assert!(target.is_ok());
    }

    #[test]
    fn test_create_sqlite_target() {
        let target = create_target("output.db");
        assert!(target.is_ok());
    }

    #[test]
    fn test_create_sqlite_target_with_table() {
        let target = create_target("output.db#mytable");
        assert!(target.is_ok());
    }

    #[test]
    fn test_create_sqlite_protocol_target() {
        let target = create_target("sqlite://output.db#mytable");
        assert!(target.is_ok());
    }

    #[test]
    fn test_create_postgres_target() {
        let target = create_target("postgres://user:pass@localhost:5432/db");
        assert!(target.is_ok());
    }

    #[test]
    fn test_create_postgres_target_with_table() {
        let target = create_target("postgres://user:pass@localhost:5432/db#mytable");
        assert!(target.is_ok());
    }

    #[test]
    fn test_create_postgresql_target() {
        let target = create_target("postgresql://user:pass@localhost:5432/db");
        assert!(target.is_ok());
    }

    #[test]
    fn test_create_mysql_target() {
        let target = create_target("mysql://user:pass@localhost:3306/db");
        assert!(target.is_ok());
    }

    #[test]
    fn test_create_mysql_target_with_table() {
        let target = create_target("mysql://user:pass@localhost:3306/db#mytable");
        assert!(target.is_ok());
    }

    #[test]
    fn test_create_unsupported_target() {
        let target = create_target("output.unsupported");
        assert!(target.is_err());
    }

    #[test]
    fn test_create_unsupported_protocol() {
        let target = create_target("redis://localhost:6379");
        assert!(target.is_err());
    }
}