tinyetl 0.12.0

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
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
use async_trait::async_trait;
use base64::{engine::general_purpose, Engine as _};
use chrono::{DateTime, Utc};
use duckdb::{
    types::{Value as OwnedValue, ValueRef},
    Connection,
};
use rust_decimal::Decimal;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use crate::{
    connectors::{row_stream::RowStream, Source, Target},
    schema::{Column as SchemaColumn, DataType, Row, Schema, Value},
    Result, TinyEtlError,
};

/// Efficient batch insert using DuckDB's Appender API
fn insert_with_appender(
    conn: &Connection,
    table_name: &str,
    rows: &[Row],
    schema: &Schema,
) -> Result<usize> {
    let mut appender = conn
        .appender(table_name)
        .map_err(|e| TinyEtlError::DataTransfer(format!("Failed to create appender: {}", e)))?;

    // Insert each row using the appender
    for row in rows {
        // Collect values in schema order as owned values
        let mut row_values: Vec<duckdb::types::Value> = Vec::new();

        for col in &schema.columns {
            let value = row.get(&col.name).unwrap_or(&Value::Null);

            let duckdb_value = match value {
                Value::String(s) => duckdb::types::Value::Text(s.clone()),
                Value::Integer(i) => duckdb::types::Value::BigInt(*i),
                // As text, which DuckDB converts exactly to the column's type (DECIMAL in
                // tables TinyETL creates, DOUBLE in older ones)
                Value::Decimal(d) => duckdb::types::Value::Text(d.to_string()),
                Value::Boolean(b) => duckdb::types::Value::Boolean(*b),
                Value::Date(dt) => {
                    // Convert datetime to string for DuckDB
                    let timestamp_str = dt.to_rfc3339();
                    duckdb::types::Value::Text(timestamp_str)
                }
                Value::Json(j) => {
                    // DuckDB can store JSON as text or use JSON type
                    let json_str = serde_json::to_string(j).unwrap_or_else(|_| "{}".to_string());
                    duckdb::types::Value::Text(json_str)
                }
                Value::Null => duckdb::types::Value::Null,
            };

            row_values.push(duckdb_value);
        }

        // Convert to refs for appender
        let params_refs: Vec<&dyn duckdb::types::ToSql> = row_values
            .iter()
            .map(|v| v as &dyn duckdb::types::ToSql)
            .collect();

        appender
            .append_row(params_refs.as_slice())
            .map_err(|e| TinyEtlError::DataTransfer(format!("Failed to append row: {}", e)))?;
    }

    // Flush the appender to commit the data
    appender
        .flush()
        .map_err(|e| TinyEtlError::DataTransfer(format!("Failed to flush appender: {}", e)))?;

    Ok(rows.len())
}

/// DuckDB source connector for reading data from DuckDB databases
pub struct DuckdbSource {
    connection_string: String,
    connection: Option<Arc<Mutex<Connection>>>,
    table_name: String,
    /// `--source-query`: read this query's result instead of the table
    query: Option<String>,
    /// One streaming `SELECT` for the whole read (no OFFSET paging), on its own thread
    stream: Option<RowStream>,
    consumed: bool,
}

impl DuckdbSource {
    pub fn new(connection_string: &str) -> Result<Self> {
        // Parse connection string - could be "file.duckdb" or "duckdb:file.duckdb#table" or "file.duckdb#table"
        let (db_path, table) = if connection_string.contains('#') {
            let parts: Vec<&str> = connection_string.split('#').collect();
            if parts.len() != 2 {
                return Err(TinyEtlError::Configuration(
                    "DuckDB connection string format: file.duckdb#table".to_string(),
                ));
            }
            (parts[0].trim_start_matches("duckdb:"), parts[1])
        } else {
            return Err(TinyEtlError::Configuration(
                "DuckDB source requires table specification: file.duckdb#table".to_string(),
            ));
        };

        Ok(Self {
            connection_string: db_path.to_string(),
            connection: None,
            table_name: table.to_string(),
            query: None,
            stream: None,
            consumed: false,
        })
    }

    /// Read the result of `query`; `connection_string` is the database file, without `#table`
    pub fn with_query(connection_string: &str, query: &str) -> Result<Self> {
        let db_path = connection_string
            .trim_start_matches("duckdb://")
            .trim_start_matches("duckdb:");
        Ok(Self {
            connection_string: db_path.to_string(),
            connection: None,
            table_name: String::new(),
            query: Some(query.to_string()),
            stream: None,
            consumed: false,
        })
    }

    /// The statement that reads every row
    fn select_sql(&self) -> String {
        match &self.query {
            Some(query) => query.clone(),
            None => format!("SELECT * FROM \"{}\"", self.table_name),
        }
    }

    /// Run `SELECT *` once on a cloned connection, on its own thread, and stream the rows.
    fn start_stream(&self) -> Result<RowStream> {
        let conn = self
            .connection
            .as_ref()
            .ok_or_else(|| TinyEtlError::Connection("Not connected".to_string()))?
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .try_clone()
            .map_err(|e| TinyEtlError::Connection(format!("Failed to open a connection: {}", e)))?;
        let sql = self.select_sql();
        RowStream::spawn_blocking(move |mut sink| {
            let result = (|| -> std::result::Result<(), String> {
                let mut stmt = conn
                    .prepare(&sql)
                    .map_err(|e| format!("Failed to prepare query: {}", e))?;
                let mut rows = stmt
                    .query([])
                    .map_err(|e| format!("Failed to execute query: {}", e))?;
                let mut names: Vec<String> = Vec::new();
                while let Some(row) = rows
                    .next()
                    .map_err(|e| format!("Failed to fetch row: {}", e))?
                {
                    if names.is_empty() {
                        let count = row.as_ref().column_count();
                        names = (0..count)
                            .map(|i| {
                                row.as_ref()
                                    .column_name(i)
                                    .map(|s| s.to_string())
                                    .unwrap_or_else(|_| format!("column_{}", i))
                            })
                            .collect();
                    }
                    let values: Row = names
                        .iter()
                        .enumerate()
                        .map(|(i, name)| (name.clone(), value_at(row, i)))
                        .collect();
                    if !sink.blocking_push(values) {
                        return Ok(()); // the reader is gone
                    }
                }
                Ok(())
            })();
            match result {
                Ok(()) => sink.blocking_finish(),
                Err(message) => sink.blocking_fail(message),
            }
        })
    }
}

/// A DuckDB value as a TinyETL value, keeping numeric and date/time types.
fn value_at(row: &duckdb::Row, i: usize) -> Value {
    let Ok(value_ref) = row.get_ref(i) else {
        return Value::Null;
    };
    match value_ref {
        ValueRef::Null => Value::Null,
        ValueRef::Boolean(b) => Value::Boolean(b),
        ValueRef::TinyInt(n) => Value::Integer(n as i64),
        ValueRef::SmallInt(n) => Value::Integer(n as i64),
        ValueRef::Int(n) => Value::Integer(n as i64),
        ValueRef::BigInt(n) => Value::Integer(n),
        ValueRef::HugeInt(n) => match i64::try_from(n) {
            Ok(n) => Value::Integer(n),
            Err(_) => Value::String(n.to_string()),
        },
        ValueRef::UTinyInt(n) => Value::Integer(n as i64),
        ValueRef::USmallInt(n) => Value::Integer(n as i64),
        ValueRef::UInt(n) => Value::Integer(n as i64),
        ValueRef::UBigInt(n) => match i64::try_from(n) {
            Ok(n) => Value::Integer(n),
            Err(_) => Value::String(n.to_string()),
        },
        ValueRef::Float(f) => match Decimal::try_from(f) {
            Ok(d) => Value::Decimal(d),
            Err(_) => Value::String(f.to_string()),
        },
        ValueRef::Double(f) => match Decimal::try_from(f) {
            Ok(d) => Value::Decimal(d),
            Err(_) => Value::String(f.to_string()),
        },
        // DECIMAL(38,10), the type TinyETL creates, would print ten decimal places
        ValueRef::Decimal(d) if d.scale() == 10 => Value::Decimal(d.normalize()),
        ValueRef::Decimal(d) => Value::Decimal(d),
        ValueRef::Timestamp(unit, value) => {
            let micros = unit.to_micros(value);
            match DateTime::<Utc>::from_timestamp_micros(micros) {
                Some(dt) => Value::Date(dt),
                None => Value::Null,
            }
        }
        ValueRef::Date32(days) => DateTime::<Utc>::from_timestamp(days as i64 * 86_400, 0)
            .map_or(Value::Null, Value::Date),
        ValueRef::Text(bytes) => match std::str::from_utf8(bytes) {
            Ok(s) => Value::String(s.to_string()),
            Err(_) => Value::Null,
        },
        ValueRef::Blob(bytes) => Value::String(general_purpose::STANDARD.encode(bytes)),
        // Lists, structs, maps and unions become JSON; enums, times and intervals text
        other => match other.to_owned() {
            v @ (OwnedValue::List(_)
            | OwnedValue::Array(_)
            | OwnedValue::Struct(_)
            | OwnedValue::Map(_)
            | OwnedValue::Union(_)) => Value::Json(to_json(v)),
            OwnedValue::Enum(text) => Value::String(text),
            OwnedValue::Time64(unit, value) => {
                let micros = unit.to_micros(value);
                chrono::NaiveTime::from_num_seconds_from_midnight_opt(
                    (micros / 1_000_000) as u32,
                    (micros % 1_000_000) as u32 * 1_000,
                )
                .map_or(Value::Null, |t| Value::String(t.to_string()))
            }
            OwnedValue::Interval {
                months,
                days,
                nanos,
            } => Value::String(interval_text(months, days, nanos)),
            _ => row.get::<_, String>(i).map_or(Value::Null, Value::String),
        },
    }
}

/// An interval as DuckDB prints it: `1 year 2 months 3 days 04:05:06`
fn interval_text(months: i32, days: i32, nanos: i64) -> String {
    let mut parts = Vec::new();
    let plural =
        |n: i64, unit: &str| format!("{} {}{}", n, unit, if n.abs() == 1 { "" } else { "s" });
    let (years, months) = (months / 12, months % 12);
    if years != 0 {
        parts.push(plural(years as i64, "year"));
    }
    if months != 0 {
        parts.push(plural(months as i64, "month"));
    }
    if days != 0 {
        parts.push(plural(days as i64, "day"));
    }
    if nanos != 0 || parts.is_empty() {
        let sign = if nanos < 0 { "-" } else { "" };
        let micros = (nanos / 1_000).abs();
        let (secs, frac) = (micros / 1_000_000, micros % 1_000_000);
        let mut time = format!(
            "{}{:02}:{:02}:{:02}",
            sign,
            secs / 3600,
            secs / 60 % 60,
            secs % 60
        );
        if frac != 0 {
            time.push_str(&format!(".{:06}", frac));
        }
        parts.push(time);
    }
    parts.join(" ")
}

/// A nested DuckDB value as JSON
fn to_json(value: OwnedValue) -> serde_json::Value {
    use serde_json::Value as Json;
    match value {
        OwnedValue::Null => Json::Null,
        OwnedValue::Boolean(b) => Json::Bool(b),
        OwnedValue::TinyInt(n) => n.into(),
        OwnedValue::SmallInt(n) => n.into(),
        OwnedValue::Int(n) => n.into(),
        OwnedValue::BigInt(n) => n.into(),
        OwnedValue::UTinyInt(n) => n.into(),
        OwnedValue::USmallInt(n) => n.into(),
        OwnedValue::UInt(n) => n.into(),
        OwnedValue::UBigInt(n) => n.into(),
        OwnedValue::HugeInt(n) => {
            i64::try_from(n).map_or_else(|_| Json::String(n.to_string()), Json::from)
        }
        OwnedValue::Float(f) => {
            serde_json::Number::from_f64(f as f64).map_or(Json::Null, Json::Number)
        }
        OwnedValue::Double(f) => serde_json::Number::from_f64(f).map_or(Json::Null, Json::Number),
        OwnedValue::Decimal(d) => serde_json::from_str(&d.to_string()).unwrap_or(Json::Null),
        OwnedValue::Text(s) | OwnedValue::Enum(s) => Json::String(s),
        OwnedValue::Blob(bytes) => Json::String(general_purpose::STANDARD.encode(bytes)),
        OwnedValue::Timestamp(unit, value) => {
            DateTime::<Utc>::from_timestamp_micros(unit.to_micros(value))
                .map_or(Json::Null, |dt| Json::String(dt.to_rfc3339()))
        }
        OwnedValue::Date32(days) => DateTime::<Utc>::from_timestamp(days as i64 * 86_400, 0)
            .map_or(Json::Null, |dt| {
                Json::String(dt.format("%Y-%m-%d").to_string())
            }),
        OwnedValue::List(items) | OwnedValue::Array(items) => {
            Json::Array(items.into_iter().map(to_json).collect())
        }
        OwnedValue::Struct(fields) => Json::Object(
            fields
                .iter()
                .map(|(k, v)| (k.clone(), to_json(v.clone())))
                .collect(),
        ),
        OwnedValue::Map(entries) => Json::Object(
            entries
                .iter()
                .map(|(k, v)| {
                    let key = match to_json(k.clone()) {
                        Json::String(s) => s,
                        other => other.to_string(),
                    };
                    (key, to_json(v.clone()))
                })
                .collect(),
        ),
        OwnedValue::Union(inner) => to_json(*inner),
        other => Json::String(format!("{:?}", other)),
    }
}

/// TinyETL type for a DuckDB column type name, as `DESCRIBE` reports it
fn column_type(duckdb_type: &str) -> DataType {
    let t = duckdb_type.trim().to_uppercase();
    // Nested types: INTEGER[], VARCHAR[3], STRUCT(...), MAP(...), UNION(...)
    if t.contains('[')
        || t.starts_with("STRUCT")
        || t.starts_with("MAP")
        || t.starts_with("UNION")
        || t == "JSON"
    {
        return DataType::Json;
    }
    match t.split('(').next().unwrap_or("").trim() {
        "TINYINT" | "SMALLINT" | "INTEGER" | "INT" | "BIGINT" | "HUGEINT" | "UTINYINT"
        | "USMALLINT" | "UINTEGER" | "UBIGINT" | "UHUGEINT" => DataType::Integer,
        "FLOAT" | "REAL" | "DOUBLE" | "DECIMAL" | "NUMERIC" => DataType::Decimal,
        "BOOLEAN" | "BOOL" => DataType::Boolean,
        "DATE" => DataType::Date,
        base if base.starts_with("TIMESTAMP") || base == "DATETIME" => DataType::DateTime,
        _ => DataType::String,
    }
}

#[async_trait]
impl Source for DuckdbSource {
    async fn connect(&mut self) -> Result<()> {
        // DuckDB connection is synchronous, but we wrap it for async compatibility
        let conn = Connection::open(&self.connection_string)
            .map_err(|e| TinyEtlError::Connection(format!(
                "Failed to connect to DuckDB database '{}': {}. Make sure the file exists and is readable.",
                self.connection_string,
                e
            )))?;

        self.connection = Some(Arc::new(Mutex::new(conn)));
        Ok(())
    }

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

        let conn = self.connection.as_ref().unwrap();
        let conn = conn.lock().unwrap();

        // Column names and types; DESCRIBE works for a query's result too, without running it
        let query = match &self.query {
            Some(query) => format!("DESCRIBE {}", query),
            None => format!("DESCRIBE \"{}\"", self.table_name),
        };
        let mut stmt = conn.prepare(&query).map_err(|e| match &self.query {
            Some(_) => TinyEtlError::DataTransfer(format!("Failed to run the query: {}", e)),
            None => TinyEtlError::DataTransfer(format!(
                "Failed to describe table '{}': {}",
                self.table_name, e
            )),
        })?;

        let rows = stmt
            .query_map([], |row| {
                Ok((
                    row.get::<_, String>(0)?, // column_name
                    row.get::<_, String>(1)?, // column_type
                    row.get::<_, String>(2)?, // null
                ))
            })
            .map_err(|e| {
                TinyEtlError::DataTransfer(format!("Failed to query table schema: {}", e))
            })?;

        let mut columns = Vec::new();
        for row_result in rows {
            let (name, duckdb_type, null_str) = row_result.map_err(|e| {
                TinyEtlError::DataTransfer(format!("Failed to read schema row: {}", e))
            })?;

            let data_type = column_type(&duckdb_type);

            let nullable = null_str.to_uppercase() == "YES";

            columns.push(SchemaColumn {
                name,
                data_type,
                nullable,
            });
        }

        // Row count for the progress bar; not for a query, where counting would run it
        let estimated_rows = if self.query.is_some() {
            None
        } else {
            let count_query = format!("SELECT COUNT(*) FROM \"{}\"", self.table_name);
            let count: i64 = conn
                .query_row(&count_query, [], |row| row.get(0))
                .map_err(|e| TinyEtlError::DataTransfer(format!("Failed to count rows: {}", e)))?;
            Some(count as usize)
        };

        Ok(Schema {
            columns,
            estimated_rows,
            primary_key_candidate: None,
        })
    }

    async fn read_batch(&mut self, batch_size: usize) -> Result<Vec<Row>> {
        if self.connection.is_none() {
            self.connect().await?;
        }
        if self.stream.is_none() {
            self.stream = Some(self.start_stream()?);
        }
        let rows = self
            .stream
            .as_mut()
            .expect("started above")
            .next_batch(batch_size)
            .await?;
        self.consumed |= !rows.is_empty();
        Ok(rows)
    }

    async fn estimated_row_count(&self) -> Result<Option<usize>> {
        if self.query.is_some() {
            return Ok(None); // counting would run the query
        }
        if let Some(conn) = &self.connection {
            let conn = conn.lock().unwrap();
            let count_query = format!("SELECT COUNT(*) FROM \"{}\"", self.table_name);
            let count: i64 = conn
                .query_row(&count_query, [], |row| row.get(0))
                .map_err(|e| TinyEtlError::DataTransfer(format!("Failed to count rows: {}", e)))?;
            Ok(Some(count as usize))
        } else {
            Ok(None)
        }
    }

    async fn reset(&mut self) -> Result<()> {
        // The query runs again on the next read, but only if rows were already read
        if self.consumed {
            self.stream = None;
            self.consumed = false;
        }
        Ok(())
    }

    fn has_more(&self) -> bool {
        self.stream.as_ref().is_none_or(RowStream::has_more)
    }
}

/// DuckDB target connector for writing data to DuckDB databases
pub struct DuckdbTarget {
    connection_string: String,
    connection: Option<Arc<Mutex<Connection>>>,
    table_name: String,
    schema: Option<Schema>, // Cache the schema to avoid re-inference
    /// The load runs in one transaction, begun at the first write and committed in
    /// finalize; dropping the target without finalize rolls it back
    in_transaction: bool,
    /// truncate() was called: empty the table inside the load's transaction
    truncate_table: Option<String>,
}

impl DuckdbTarget {
    /// Open the load's transaction (once), emptying the table first if --truncate was given.
    fn begin(&mut self) -> Result<()> {
        if self.in_transaction {
            return Ok(());
        }
        let conn = self
            .connection
            .as_ref()
            .ok_or_else(|| TinyEtlError::Connection("Connection not established".to_string()))?
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        conn.execute_batch("BEGIN TRANSACTION").map_err(|e| {
            TinyEtlError::DataTransfer(format!("Failed to start a transaction: {}", e))
        })?;
        if let Some(table) = self.truncate_table.take() {
            conn.execute(&format!("DELETE FROM \"{}\"", table), [])
                .map_err(|e| {
                    TinyEtlError::DataTransfer(format!("Failed to truncate table: {}", e))
                })?;
        }
        drop(conn);
        self.in_transaction = true;
        Ok(())
    }
}

impl Drop for DuckdbTarget {
    fn drop(&mut self) {
        // The transfer failed before finalize: undo the partial load
        if self.in_transaction {
            if let Some(conn) = &self.connection {
                let conn = conn.lock().unwrap_or_else(|e| e.into_inner());
                let _ = conn.execute_batch("ROLLBACK");
            }
        }
    }
}

impl DuckdbTarget {
    pub fn new(connection_string: &str) -> Result<Self> {
        // Parse connection string - support multiple formats:
        // - "file.duckdb" or "file.duckdb#table" (legacy)
        // - "duckdb:file.duckdb" or "duckdb:file.duckdb#table"
        let normalized = connection_string.trim_start_matches("duckdb:");

        let (db_path, table) = if normalized.contains('#') {
            let parts: Vec<&str> = normalized.split('#').collect();
            if parts.len() != 2 {
                return Err(TinyEtlError::Configuration(
                    "DuckDB connection string format: file.duckdb#table or duckdb:file.duckdb#table".to_string()
                ));
            }
            (parts[0], parts[1])
        } else {
            // Default table name if not specified
            (normalized, "data")
        };

        Ok(Self {
            connection_string: db_path.to_string(),
            connection: None,
            table_name: table.to_string(),
            schema: None,
            in_transaction: false,
            truncate_table: None,
        })
    }

    fn get_db_path(&self) -> Result<PathBuf> {
        Ok(PathBuf::from(&self.connection_string))
    }

    fn map_data_type_to_duckdb(&self, data_type: &DataType) -> &'static str {
        match data_type {
            DataType::Integer => "BIGINT",
            // Exact, so sums of money in a SQL transform don't pick up float noise
            DataType::Decimal => "DECIMAL(38,10)",
            DataType::String => "VARCHAR",
            DataType::Boolean => "BOOLEAN",
            DataType::Date => "DATE",
            DataType::DateTime => "TIMESTAMP",
            DataType::Json => "JSON", // DuckDB has native JSON type
            DataType::Null => "VARCHAR",
        }
    }
}

#[async_trait]
impl Target for DuckdbTarget {
    async fn connect(&mut self) -> Result<()> {
        // Ensure parent directory exists for the database file
        let db_path = self.get_db_path()?;
        if let Some(parent) = db_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        // DuckDB will automatically create the database file if it doesn't exist
        let conn = Connection::open(&self.connection_string).map_err(|e| {
            TinyEtlError::Connection(format!(
                "Failed to connect to DuckDB database '{}': {}. Check file path and permissions.",
                db_path.display(),
                e
            ))
        })?;

        self.connection = Some(Arc::new(Mutex::new(conn)));
        Ok(())
    }

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

        let conn = self.connection.as_ref().unwrap();
        let conn = conn.lock().unwrap();

        // Determine the actual table name to use
        let actual_table_name = if table_name.is_empty() {
            self.table_name.clone()
        } else {
            table_name.to_string()
        };

        // Update our internal table name to match what we're actually creating
        self.table_name = actual_table_name.clone();

        // Store the schema for efficient Arrow-based writes
        self.schema = Some(schema.clone());

        // Build CREATE TABLE statement with IF NOT EXISTS (append-first philosophy)
        let column_definitions: Vec<String> = schema
            .columns
            .iter()
            .map(|col| {
                let duckdb_type = self.map_data_type_to_duckdb(&col.data_type);
                let nullable = if col.nullable { "" } else { " NOT NULL" };
                format!("\"{}\" {}{}", col.name, duckdb_type, nullable)
            })
            .collect();

        // Use CREATE TABLE IF NOT EXISTS to support append-first philosophy
        let create_sql = format!(
            "CREATE TABLE IF NOT EXISTS \"{}\" ({})",
            actual_table_name,
            column_definitions.join(", ")
        );

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

        Ok(())
    }

    async fn write_batch(&mut self, rows: &[Row]) -> Result<usize> {
        if self.connection.is_none() {
            return Err(TinyEtlError::Connection(
                "Connection not established".to_string(),
            ));
        }

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

        let conn = self.connection.as_ref().unwrap();
        let conn = conn.lock().unwrap();

        // Use cached schema if available, otherwise infer from rows
        let schema = match &self.schema {
            Some(s) => s.clone(),
            None => {
                // Fallback: infer schema from rows (less efficient)
                crate::schema::SchemaInferer::infer_from_rows(rows)?
            }
        };

        // Use DuckDB's high-performance Appender API for batch insertion
        let affected = insert_with_appender(&conn, &self.table_name, rows, &schema)?;

        Ok(affected)
    }

    async fn finalize(&mut self) -> Result<()> {
        // A --truncate with no rows to load still has to empty the table
        if self.truncate_table.is_some() {
            self.begin()?;
        }
        if self.in_transaction {
            let conn = self.connection.as_ref().unwrap();
            let conn = conn.lock().unwrap_or_else(|e| e.into_inner());
            conn.execute_batch("COMMIT").map_err(|e| {
                TinyEtlError::DataTransfer(format!("Failed to commit the load: {}", e))
            })?;
            drop(conn);
            self.in_transaction = false;
        }
        Ok(())
    }

    async fn exists(&self, table_name: &str) -> Result<bool> {
        if let Some(conn) = &self.connection {
            let conn = conn.lock().unwrap();
            let actual_table_name = if table_name.is_empty() {
                &self.table_name
            } else {
                table_name
            };

            let query = "SELECT table_name FROM information_schema.tables WHERE table_name = ?";
            let result = conn.query_row(query, [actual_table_name], |_| Ok(true));

            Ok(result.unwrap_or(false))
        } else {
            Ok(false)
        }
    }

    async fn truncate(&mut self, table_name: &str) -> Result<()> {
        // Deferred into the load's transaction, so a failed load keeps the old rows
        let table = if table_name.is_empty() {
            &self.table_name
        } else {
            table_name
        };
        self.truncate_table = Some(table.to_string());
        Ok(())
    }

    fn supports_append(&self) -> bool {
        // DuckDB databases support appending new rows
        true
    }
}

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

    #[test]
    fn test_column_type() {
        assert_eq!(column_type("INTEGER"), DataType::Integer);
        assert_eq!(column_type("INTEGER[]"), DataType::Json);
        assert_eq!(column_type("STRUCT(n BIGINT)"), DataType::Json);
        assert_eq!(column_type("MAP(VARCHAR, INTEGER)"), DataType::Json);
        assert_eq!(column_type("INTERVAL"), DataType::String);
        assert_eq!(column_type("DECIMAL(18,3)"), DataType::Decimal);
        assert_eq!(column_type("TIMESTAMP WITH TIME ZONE"), DataType::DateTime);
        assert_eq!(column_type("DATE"), DataType::Date);
        assert_eq!(column_type("JSON"), DataType::Json);
        assert_eq!(column_type("VARCHAR"), DataType::String);
    }

    #[test]
    fn test_interval_text() {
        assert_eq!(interval_text(0, 3, 0), "3 days");
        assert_eq!(
            interval_text(14, 1, 3_723_000_000_000),
            "1 year 2 months 1 day 01:02:03"
        );
        assert_eq!(interval_text(0, 0, 1_500_000), "00:00:00.001500");
        assert_eq!(interval_text(0, 0, 0), "00:00:00");
    }

    #[tokio::test]
    async fn test_database_contract() {
        let dir = tempfile::tempdir().unwrap();
        let url = format!("{}#t", dir.path().join("contract.duckdb").display());
        let source_url = url.clone();
        crate::connectors::db_contract::run_all(
            Box::new(move || Box::new(DuckdbSource::new(&source_url).unwrap())),
            Box::new(move || Box::new(DuckdbTarget::new(&url).unwrap())),
        )
        .await;
    }

    #[test]
    fn test_duckdb_source_new() {
        let source = DuckdbSource::new("test.duckdb#users");
        assert!(source.is_ok());
    }

    #[test]
    fn test_duckdb_source_invalid_format() {
        let source = DuckdbSource::new("test.duckdb");
        assert!(source.is_err());
    }

    #[test]
    fn test_duckdb_target_new() {
        let target = DuckdbTarget::new("test.duckdb#users");
        assert!(target.is_ok());

        let target2 = DuckdbTarget::new("test.duckdb");
        assert!(target2.is_ok());
    }
}