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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
use crate::Result;
use arrow::datatypes::{DataType as ArrowDataType, Field, TimeUnit};
use chrono::{DateTime, Utc};
use regex::Regex;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

/// Wrapper around Arrow DataType for schema definition
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum DataType {
    String,
    Integer,
    Decimal,
    Boolean,
    Date,
    DateTime,
    Json,
    Null,
}

impl DataType {
    /// Convert to Arrow DataType
    pub fn to_arrow(&self) -> ArrowDataType {
        match self {
            DataType::String => ArrowDataType::Utf8,
            DataType::Integer => ArrowDataType::Int64,
            DataType::Decimal => ArrowDataType::Float64, // Could also use Decimal128
            DataType::Boolean => ArrowDataType::Boolean,
            DataType::Date => ArrowDataType::Date64,
            DataType::DateTime => ArrowDataType::Timestamp(TimeUnit::Nanosecond, None),
            DataType::Json => ArrowDataType::Utf8, // Store JSON as string in Arrow
            DataType::Null => ArrowDataType::Null,
        }
    }

    /// Convert from Arrow DataType
    pub fn from_arrow(arrow_type: &ArrowDataType) -> Self {
        match arrow_type {
            ArrowDataType::Utf8 | ArrowDataType::LargeUtf8 => DataType::String,
            ArrowDataType::Int8
            | ArrowDataType::Int16
            | ArrowDataType::Int32
            | ArrowDataType::Int64 => DataType::Integer,
            ArrowDataType::UInt8
            | ArrowDataType::UInt16
            | ArrowDataType::UInt32
            | ArrowDataType::UInt64 => DataType::Integer,
            ArrowDataType::Float16 | ArrowDataType::Float32 | ArrowDataType::Float64 => {
                DataType::Decimal
            }
            ArrowDataType::Decimal128(_, _) | ArrowDataType::Decimal256(_, _) => DataType::Decimal,
            ArrowDataType::Boolean => DataType::Boolean,
            ArrowDataType::Date32 | ArrowDataType::Date64 => DataType::Date,
            ArrowDataType::Timestamp(_, _) => DataType::DateTime,
            ArrowDataType::Null => DataType::Null,
            _ => DataType::String, // Default to string for complex types
        }
    }
}

fn default_nullable() -> bool {
    true
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaFileColumn {
    pub name: String,
    #[serde(rename = "type")]
    pub data_type: String,
    #[serde(default = "default_nullable")]
    pub nullable: bool,
    pub pattern: Option<String>,
    pub default: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaFile {
    pub columns: Vec<SchemaFileColumn>,
}

impl SchemaFile {
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let content = std::fs::read_to_string(path)?;
        let schema_file: SchemaFile = serde_yaml::from_str(&content).map_err(|e| {
            crate::TinyEtlError::Configuration(format!("Invalid schema file: {}", e))
        })?;

        // Validate the schema file
        schema_file.validate()?;

        Ok(schema_file)
    }

    pub fn validate(&self) -> Result<()> {
        for column in &self.columns {
            // Validate data type
            match column.data_type.to_lowercase().as_str() {
                "string" | "integer" | "decimal" | "boolean" | "date" | "datetime" | "json" => {}
                _ => {
                    return Err(crate::TinyEtlError::Configuration(format!(
                        "Invalid data type '{}' for column '{}'",
                        column.data_type, column.name
                    )))
                }
            }

            // Validate regex pattern if provided
            if let Some(pattern) = &column.pattern {
                Regex::new(pattern).map_err(|e| {
                    crate::TinyEtlError::Configuration(format!(
                        "Invalid regex pattern '{}' for column '{}': {}",
                        pattern, column.name, e
                    ))
                })?;
            }
        }
        Ok(())
    }

    pub fn to_schema(&self) -> Result<Schema> {
        let columns = self
            .columns
            .iter()
            .map(|col| {
                let data_type = match col.data_type.to_lowercase().as_str() {
                    "string" => DataType::String,
                    "integer" => DataType::Integer,
                    "decimal" => DataType::Decimal,
                    "boolean" => DataType::Boolean,
                    "date" => DataType::Date,
                    "datetime" => DataType::DateTime,
                    "json" => DataType::Json,
                    _ => DataType::String, // Already validated, so this shouldn't happen
                };

                Column {
                    name: col.name.clone(),
                    data_type,
                    nullable: col.nullable,
                }
            })
            .collect();

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

    pub fn validate_and_transform_row(&self, row: &mut Row) -> Result<()> {
        for schema_col in &self.columns {
            let value = row.get(&schema_col.name);

            // Check for required columns
            if !schema_col.nullable && (value.is_none() || matches!(value, Some(Value::Null))) {
                // Apply default if available
                if let Some(default_str) = &schema_col.default {
                    let default_value =
                        self.parse_default_value(default_str, &schema_col.data_type)?;
                    row.insert(schema_col.name.clone(), default_value);
                } else {
                    return Err(crate::TinyEtlError::DataValidation(format!(
                        "Required column '{}' is missing or null",
                        schema_col.name
                    )));
                }
            }

            // Transform and validate existing values
            if let Some(val) = row.get(&schema_col.name).cloned() {
                // Convert string to JSON if schema expects JSON type
                let transformed_val = if schema_col.data_type.to_lowercase() == "json"
                    && matches!(val, Value::String(_))
                {
                    if let Value::String(s) = val {
                        // Try to parse the string as JSON
                        match serde_json::from_str::<serde_json::Value>(&s) {
                            Ok(json_val) => Value::Json(json_val),
                            Err(e) => {
                                return Err(crate::TinyEtlError::DataValidation(format!(
                                    "Column '{}' contains invalid JSON: {}",
                                    schema_col.name, e
                                )));
                            }
                        }
                    } else {
                        val
                    }
                } else {
                    val
                };

                // Update the row with the transformed value
                row.insert(schema_col.name.clone(), transformed_val.clone());

                // Validate the transformed value
                self.validate_column_value(&transformed_val, schema_col)?;
            }
        }
        Ok(())
    }

    fn validate_column_value(&self, value: &Value, schema_col: &SchemaFileColumn) -> Result<()> {
        // Skip null values if column is nullable
        if matches!(value, Value::Null) && schema_col.nullable {
            return Ok(());
        }

        // Validate data type
        let expected_type = match schema_col.data_type.to_lowercase().as_str() {
            "string" => DataType::String,
            "integer" => DataType::Integer,
            "decimal" => DataType::Decimal,
            "boolean" => DataType::Boolean,
            "date" => DataType::Date,
            "datetime" => DataType::DateTime,
            "json" => DataType::Json,
            _ => {
                return Err(crate::TinyEtlError::DataValidation(format!(
                    "Unknown data type '{}' for column '{}'",
                    schema_col.data_type, schema_col.name
                )))
            }
        };

        let actual_type = SchemaInferer::infer_type(value);
        if actual_type != expected_type && actual_type != DataType::Null {
            return Err(crate::TinyEtlError::DataValidation(format!(
                "Column '{}' expected type {:?}, got {:?}",
                schema_col.name, expected_type, actual_type
            )));
        }

        // Validate pattern for string values
        if let (Some(pattern), Value::String(s)) = (&schema_col.pattern, value) {
            let regex = Regex::new(pattern).unwrap(); // Already validated in validate()
            if !regex.is_match(s) {
                return Err(crate::TinyEtlError::DataValidation(format!(
                    "Column '{}' value '{}' does not match pattern '{}'",
                    schema_col.name, s, pattern
                )));
            }
        }

        Ok(())
    }

    fn parse_default_value(&self, default_str: &str, data_type: &str) -> Result<Value> {
        match data_type.to_lowercase().as_str() {
            "string" => Ok(Value::String(default_str.to_string())),
            "integer" => {
                let parsed = default_str.parse::<i64>().map_err(|_| {
                    crate::TinyEtlError::Configuration(format!(
                        "Invalid default integer value: '{}'",
                        default_str
                    ))
                })?;
                Ok(Value::Integer(parsed))
            }
            "decimal" => {
                let parsed = default_str.parse::<Decimal>().map_err(|_| {
                    crate::TinyEtlError::Configuration(format!(
                        "Invalid default decimal value: '{}'",
                        default_str
                    ))
                })?;
                Ok(Value::Decimal(parsed))
            }
            "boolean" => {
                let parsed = default_str.parse::<bool>().map_err(|_| {
                    crate::TinyEtlError::Configuration(format!(
                        "Invalid default boolean value: '{}'",
                        default_str
                    ))
                })?;
                Ok(Value::Boolean(parsed))
            }
            "date" | "datetime" => {
                // Try to parse as RFC3339 first, then as date
                let parsed = chrono::DateTime::parse_from_rfc3339(default_str)
                    .or_else(|_| {
                        // Try parsing as date only
                        chrono::NaiveDate::parse_from_str(default_str, "%Y-%m-%d")
                            .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc().fixed_offset())
                    })
                    .map_err(|_| {
                        crate::TinyEtlError::Configuration(format!(
                            "Invalid default date/datetime value: '{}'",
                            default_str
                        ))
                    })?;
                Ok(Value::Date(parsed.with_timezone(&Utc)))
            }
            "json" => {
                let parsed = serde_json::from_str(default_str).map_err(|e| {
                    crate::TinyEtlError::Configuration(format!(
                        "Invalid default JSON value: '{}' - {}",
                        default_str, e
                    ))
                })?;
                Ok(Value::Json(parsed))
            }
            _ => Err(crate::TinyEtlError::Configuration(format!(
                "Unsupported data type for default value: '{}'",
                data_type
            ))),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Column {
    pub name: String,
    pub data_type: DataType,
    pub nullable: bool,
}

impl Column {
    /// Convert to Arrow Field
    pub fn to_arrow_field(&self) -> Field {
        let mut field = Field::new(&self.name, self.data_type.to_arrow(), self.nullable);

        // Add metadata for JSON type so we can preserve it when reading back from Parquet
        if matches!(self.data_type, DataType::Json) {
            let mut metadata = std::collections::HashMap::new();
            metadata.insert("tinyetl:type".to_string(), "json".to_string());
            field = field.with_metadata(metadata);
        }

        field
    }

    /// Convert from Arrow Field
    pub fn from_arrow_field(field: &Field) -> Self {
        Self {
            name: field.name().clone(),
            data_type: DataType::from_arrow(field.data_type()),
            nullable: field.is_nullable(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Schema {
    pub columns: Vec<Column>,
    pub estimated_rows: Option<usize>,
    pub primary_key_candidate: Option<String>,
}

impl Schema {
    /// Convert to Arrow Schema
    pub fn to_arrow_schema(&self) -> arrow::datatypes::Schema {
        let fields: Vec<Field> = self
            .columns
            .iter()
            .map(|col| col.to_arrow_field())
            .collect();
        arrow::datatypes::Schema::new(fields)
    }

    /// Convert from Arrow Schema
    pub fn from_arrow_schema(arrow_schema: &arrow::datatypes::Schema) -> Self {
        let columns: Vec<Column> = arrow_schema
            .fields()
            .iter()
            .map(|field| Column::from_arrow_field(field))
            .collect();

        Self {
            columns,
            estimated_rows: None,
            primary_key_candidate: None,
        }
    }
}

/// Value type compatible with Arrow data representation
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Value {
    String(String),
    Integer(i64),
    Decimal(Decimal),
    Boolean(bool),
    Date(DateTime<Utc>),
    Json(serde_json::Value),
    Null,
}

impl Value {
    /// Get the corresponding Arrow DataType for this value
    pub fn arrow_type(&self) -> ArrowDataType {
        match self {
            Value::String(_) => ArrowDataType::Utf8,
            Value::Integer(_) => ArrowDataType::Int64,
            Value::Decimal(_) => ArrowDataType::Float64,
            Value::Boolean(_) => ArrowDataType::Boolean,
            Value::Date(_) => ArrowDataType::Timestamp(TimeUnit::Nanosecond, None),
            Value::Json(_) => ArrowDataType::Utf8, // Store JSON as string in Arrow
            Value::Null => ArrowDataType::Null,
        }
    }

    /// Convert to string representation for Arrow array building
    pub fn to_string_for_arrow(&self) -> Option<String> {
        match self {
            Value::String(s) => Some(s.clone()),
            Value::Integer(i) => Some(i.to_string()),
            Value::Decimal(d) => Some(d.to_string()),
            Value::Boolean(b) => Some(b.to_string()),
            Value::Date(dt) => Some(dt.to_rfc3339()),
            Value::Json(j) => Some(serde_json::to_string(j).unwrap_or_else(|_| "{}".to_string())),
            Value::Null => None,
        }
    }

    /// Convert to i64 for Arrow array building
    pub fn to_i64(&self) -> Option<i64> {
        match self {
            Value::Integer(i) => Some(*i),
            _ => None,
        }
    }

    /// Convert to f64 for Arrow array building
    pub fn to_f64(&self) -> Option<f64> {
        match self {
            Value::Decimal(d) => (*d).try_into().ok(),
            _ => None,
        }
    }

    /// Convert to bool for Arrow array building
    pub fn to_bool(&self) -> Option<bool> {
        match self {
            Value::Boolean(b) => Some(*b),
            _ => None,
        }
    }

    /// Convert to timestamp nanoseconds for Arrow array building
    pub fn to_timestamp_nanos(&self) -> Option<i64> {
        match self {
            Value::Date(dt) => dt.timestamp_nanos_opt(),
            _ => None,
        }
    }

    /// Convert to JSON value
    pub fn to_json(&self) -> Option<&serde_json::Value> {
        match self {
            Value::Json(j) => Some(j),
            _ => None,
        }
    }

    /// Whether this value can be stored as-is in a column of type `data_type`.
    pub fn fits(&self, data_type: &DataType) -> bool {
        matches!(
            (self, data_type),
            (Value::Null, _)
                | (Value::String(_), DataType::String | DataType::Null)
                | (Value::Integer(_), DataType::Integer)
                | (Value::Decimal(_), DataType::Decimal)
                | (Value::Boolean(_), DataType::Boolean)
                | (Value::Date(_), DataType::Date | DataType::DateTime)
                | (Value::Json(_), DataType::Json)
        )
    }

    /// Convert this value to `data_type` without losing information, so every value in a
    /// column has the column's type. Schemas are inferred from a sample, so later rows can
    /// disagree (an integer in a decimal column, a number in a text column).
    ///
    /// - Anything converts to text.
    /// - Text converts when it parses as the column's type; blank text in a non-text
    ///   column becomes NULL.
    /// - Integers widen to decimals; decimals with no fractional part narrow to integers.
    /// - Numbers and booleans become JSON scalars.
    ///
    /// A value that can't convert is returned unchanged; targets that need exact types
    /// report it.
    pub fn coerce_to(self, data_type: &DataType) -> Value {
        if self.fits(data_type) {
            return self;
        }
        match (self, data_type) {
            (value, DataType::String | DataType::Null) => {
                Value::String(value.to_string_for_arrow().unwrap_or_default())
            }
            (Value::String(s), _) if s.trim().is_empty() => Value::Null,
            (Value::String(s), DataType::Integer) => match s.trim().parse::<i64>() {
                Ok(i) => Value::Integer(i),
                Err(_) => Value::String(s),
            },
            (Value::String(s), DataType::Decimal) => match s.trim().parse::<Decimal>() {
                Ok(d) => Value::Decimal(d),
                Err(_) => Value::String(s),
            },
            (Value::String(s), DataType::Boolean) => match s.trim().to_ascii_lowercase().as_str() {
                "true" => Value::Boolean(true),
                "false" => Value::Boolean(false),
                _ => Value::String(s),
            },
            (Value::String(s), DataType::Date | DataType::DateTime) => {
                match crate::date_parser::DateParser::try_parse(&s) {
                    Some(date @ Value::Date(_)) => date,
                    _ => Value::String(s),
                }
            }
            (Value::String(s), DataType::Json) => match serde_json::from_str(&s) {
                Ok(json) => Value::Json(json),
                Err(_) => Value::String(s),
            },
            (Value::Integer(i), DataType::Decimal) => Value::Decimal(Decimal::from(i)),
            (Value::Decimal(d), DataType::Integer) if d.fract().is_zero() => {
                match i64::try_from(d) {
                    Ok(i) => Value::Integer(i),
                    Err(_) => Value::Decimal(d),
                }
            }
            (Value::Integer(i), DataType::Json) => Value::Json(i.into()),
            (Value::Decimal(d), DataType::Json) => {
                match f64::try_from(d).ok().and_then(serde_json::Number::from_f64) {
                    Some(n) => Value::Json(n.into()),
                    None => Value::Decimal(d),
                }
            }
            (Value::Boolean(b), DataType::Json) => Value::Json(b.into()),
            (value, _) => value,
        }
    }
}

/// Convert each value in `row` to its column's type with [`Value::coerce_to`].
pub fn coerce_row(row: &mut Row, schema: &Schema) {
    for column in &schema.columns {
        if let Some(value) = row.get_mut(&column.name) {
            if !value.fits(&column.data_type) {
                let owned = std::mem::replace(value, Value::Null);
                *value = owned.coerce_to(&column.data_type);
            }
        }
    }
}

pub type Row = HashMap<String, Value>;

pub struct SchemaInferer;

impl SchemaInferer {
    /// Infers a schema from sample rows. Rows are hash maps and carry no column order, so the
    /// columns come out sorted by name; sources that know their column order should call
    /// [`SchemaInferer::infer_from_rows_ordered`] instead.
    pub fn infer_from_rows(rows: &[Row]) -> Result<Schema> {
        Self::infer_from_rows_ordered(rows, &[])
    }

    /// Infers a schema from sample rows, with columns in `column_order` (for example a CSV
    /// header or a query's result columns). Columns found in the rows but missing from
    /// `column_order` follow, sorted by name; names in `column_order` that appear in no row
    /// are skipped.
    pub fn infer_from_rows_ordered(rows: &[Row], column_order: &[String]) -> Result<Schema> {
        if rows.is_empty() {
            // No data to infer types from (e.g. a CSV with only a header): keep the known
            // columns as nullable text, so targets still get a usable table
            return Ok(Schema {
                columns: column_order
                    .iter()
                    .map(|name| Column {
                        name: name.clone(),
                        data_type: DataType::String,
                        nullable: true,
                    })
                    .collect(),
                estimated_rows: Some(0),
                primary_key_candidate: None,
            });
        }

        let present: std::collections::HashSet<&String> =
            rows.iter().flat_map(|row| row.keys()).collect();
        let mut seen = std::collections::HashSet::new();
        let mut names: Vec<&String> = column_order
            .iter()
            .filter(|name| present.contains(name) && seen.insert(*name))
            .collect();
        let mut rest: Vec<&String> = present
            .into_iter()
            .filter(|name| !seen.contains(name))
            .collect();
        rest.sort();
        names.extend(rest);

        let columns = names
            .into_iter()
            .map(|col_name| {
                let types: Vec<DataType> = rows
                    .iter()
                    .map(|row| match row.get(col_name) {
                        // Blank text says nothing about the column's type; it becomes NULL
                        // in a non-text column (see Value::coerce_to)
                        Some(Value::String(s)) if s.trim().is_empty() => DataType::Null,
                        Some(value) => Self::infer_type(value),
                        None => DataType::Null,
                    })
                    .collect();
                let (data_type, nullable) = Self::resolve_column_type(&types);
                Column {
                    name: col_name.clone(),
                    data_type,
                    nullable,
                }
            })
            .collect();

        Ok(Schema {
            columns,
            estimated_rows: Some(rows.len()),
            primary_key_candidate: None, // TODO: Implement PK detection
        })
    }

    pub fn infer_type(value: &Value) -> DataType {
        match value {
            Value::String(_) => DataType::String,
            Value::Integer(_) => DataType::Integer,
            Value::Decimal(_) => DataType::Decimal,
            Value::Boolean(_) => DataType::Boolean,
            Value::Date(_) => DataType::DateTime,
            Value::Json(_) => DataType::Json,
            Value::Null => DataType::Null,
        }
    }

    pub fn resolve_column_type(types: &[DataType]) -> (DataType, bool) {
        // Filter out nulls for type determination
        let non_null_types: Vec<&DataType> = types
            .iter()
            .filter(|t| !matches!(t, DataType::Null))
            .collect();

        if non_null_types.is_empty() {
            return (DataType::String, true);
        }

        // If all non-null values are the same type, use that type
        let first_type = non_null_types[0];
        let resolved_type = if non_null_types
            .iter()
            .all(|t| std::mem::discriminant(*t) == std::mem::discriminant(first_type))
        {
            first_type.clone()
        } else if non_null_types
            .iter()
            .all(|t| matches!(t, DataType::Integer | DataType::Decimal))
        {
            // Whole and fractional numbers in one column (e.g. 84 and 29.85)
            DataType::Decimal
        } else {
            // Mixed types default to String
            DataType::String
        };

        // IMPORTANT: Always return nullable=true when inferring from sample data.
        // We cannot be certain that unseen data doesn't contain NULLs, and it's safer
        // for ETL operations to allow NULLs than to create NOT NULL constraints that
        // might be violated by subsequent batches or data that wasn't in the sample.
        (resolved_type, true)
    }
}

impl std::fmt::Display for DataType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DataType::String => write!(f, "TEXT"),
            DataType::Integer => write!(f, "INTEGER"),
            DataType::Decimal => write!(f, "DECIMAL"),
            DataType::Boolean => write!(f, "BOOLEAN"),
            DataType::Date => write!(f, "DATE"),
            DataType::DateTime => write!(f, "TIMESTAMP"),
            DataType::Json => write!(f, "JSON"),
            DataType::Null => write!(f, "NULL"),
        }
    }
}

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

    #[test]
    fn test_empty_schema_inference() {
        let rows = Vec::new();
        let schema = SchemaInferer::infer_from_rows(&rows).unwrap();
        assert!(schema.columns.is_empty());
        assert_eq!(schema.estimated_rows, Some(0));
    }

    #[test]
    fn test_single_row_schema_inference() {
        let mut row = HashMap::new();
        row.insert("id".to_string(), Value::Integer(1));
        row.insert("name".to_string(), Value::String("test".to_string()));
        row.insert("active".to_string(), Value::Boolean(true));

        let schema = SchemaInferer::infer_from_rows(&[row]).unwrap();
        assert_eq!(schema.columns.len(), 3);

        let id_col = schema.columns.iter().find(|c| c.name == "id").unwrap();
        assert_eq!(id_col.data_type, DataType::Integer);
        assert!(id_col.nullable); // Always nullable when inferred from sample data
    }

    fn column_names(schema: &Schema) -> Vec<&str> {
        schema.columns.iter().map(|c| c.name.as_str()).collect()
    }

    #[test]
    fn test_infer_from_rows_ordered_keeps_given_order() {
        let mut row1 = HashMap::new();
        row1.insert("last_name".to_string(), Value::String("Smith".to_string()));
        row1.insert("customer_id".to_string(), Value::Integer(1));
        row1.insert("zeta".to_string(), Value::Integer(9));
        let mut row2 = row1.clone();
        // A column only some rows have, missing from the order: goes after the ordered ones
        row2.insert("extra".to_string(), Value::Boolean(true));

        let order: Vec<String> = ["zeta", "customer_id", "not_in_rows", "last_name", "zeta"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let schema = SchemaInferer::infer_from_rows_ordered(&[row1, row2], &order).unwrap();

        // "not_in_rows" is skipped and the duplicate "zeta" appears once
        assert_eq!(
            column_names(&schema),
            ["zeta", "customer_id", "last_name", "extra"]
        );
        let extra = schema.columns.iter().find(|c| c.name == "extra").unwrap();
        assert_eq!(extra.data_type, DataType::Boolean);
        assert!(extra.nullable);
    }

    #[test]
    fn test_infer_from_rows_is_sorted_by_name() {
        let mut row = HashMap::new();
        for name in ["delta", "alpha", "charlie", "bravo"] {
            row.insert(name.to_string(), Value::Integer(1));
        }
        let schema = SchemaInferer::infer_from_rows(&[row]).unwrap();
        assert_eq!(
            column_names(&schema),
            ["alpha", "bravo", "charlie", "delta"]
        );
    }

    #[test]
    fn test_mixed_types_schema_inference() {
        let mut row1 = HashMap::new();
        row1.insert("value".to_string(), Value::Integer(1));

        let mut row2 = HashMap::new();
        row2.insert("value".to_string(), Value::String("hello".to_string()));

        let schema = SchemaInferer::infer_from_rows(&[row1, row2]).unwrap();
        let value_col = schema.columns.iter().find(|c| c.name == "value").unwrap();
        assert_eq!(value_col.data_type, DataType::String);
    }

    #[test]
    fn test_nullable_column_inference() {
        let mut row1 = HashMap::new();
        row1.insert("optional".to_string(), Value::String("present".to_string()));

        let mut row2 = HashMap::new();
        row2.insert("optional".to_string(), Value::Null);

        let schema = SchemaInferer::infer_from_rows(&[row1, row2]).unwrap();
        let optional_col = schema
            .columns
            .iter()
            .find(|c| c.name == "optional")
            .unwrap();
        assert_eq!(optional_col.data_type, DataType::String);
        assert!(optional_col.nullable);
    }

    #[test]
    fn test_data_type_display() {
        assert_eq!(DataType::String.to_string(), "TEXT");
        assert_eq!(DataType::Integer.to_string(), "INTEGER");
        assert_eq!(DataType::Decimal.to_string(), "DECIMAL");
        assert_eq!(DataType::Boolean.to_string(), "BOOLEAN");
        assert_eq!(DataType::Date.to_string(), "DATE");
        assert_eq!(DataType::DateTime.to_string(), "TIMESTAMP");
        assert_eq!(DataType::Json.to_string(), "JSON");
        assert_eq!(DataType::Null.to_string(), "NULL");
    }

    #[test]
    fn test_value_type_inference() {
        assert_eq!(
            SchemaInferer::infer_type(&Value::String("test".to_string())),
            DataType::String
        );
        assert_eq!(
            SchemaInferer::infer_type(&Value::Integer(42)),
            DataType::Integer
        );
        assert_eq!(
            SchemaInferer::infer_type(&Value::Decimal(Decimal::new(314, 2))),
            DataType::Decimal
        );
        assert_eq!(
            SchemaInferer::infer_type(&Value::Boolean(true)),
            DataType::Boolean
        );
        assert_eq!(
            SchemaInferer::infer_type(&Value::Date(Utc::now())),
            DataType::DateTime
        );
        assert_eq!(
            SchemaInferer::infer_type(&Value::Json(serde_json::json!({"key": "value"}))),
            DataType::Json
        );
        assert_eq!(SchemaInferer::infer_type(&Value::Null), DataType::Null);
    }

    #[test]
    fn test_column_type_resolution() {
        // All same type - but still nullable when inferred
        let types = vec![DataType::Integer, DataType::Integer, DataType::Integer];
        let (resolved_type, nullable) = SchemaInferer::resolve_column_type(&types);
        assert_eq!(resolved_type, DataType::Integer);
        assert!(nullable); // Always nullable when inferring from sample data

        // With nulls
        let types = vec![DataType::String, DataType::Null, DataType::String];
        let (resolved_type, nullable) = SchemaInferer::resolve_column_type(&types);
        assert_eq!(resolved_type, DataType::String);
        assert!(nullable);

        // All nulls
        let types = vec![DataType::Null, DataType::Null];
        let (resolved_type, nullable) = SchemaInferer::resolve_column_type(&types);
        assert_eq!(resolved_type, DataType::String);
        assert!(nullable);

        // Whole and fractional numbers make a decimal column
        let types = vec![DataType::Decimal, DataType::Integer, DataType::Null];
        let (resolved_type, _) = SchemaInferer::resolve_column_type(&types);
        assert_eq!(resolved_type, DataType::Decimal);

        // Numbers mixed with anything else stay text
        let types = vec![DataType::Integer, DataType::Boolean];
        let (resolved_type, _) = SchemaInferer::resolve_column_type(&types);
        assert_eq!(resolved_type, DataType::String);
    }

    #[test]
    fn test_coerce_to_column_type() {
        use std::str::FromStr;
        let dec = |s: &str| Value::Decimal(Decimal::from_str(s).unwrap());

        // Widen, narrow, and leave what doesn't convert
        assert_eq!(Value::Integer(84).coerce_to(&DataType::Decimal), dec("84"));
        assert_eq!(
            dec("12.00").coerce_to(&DataType::Integer),
            Value::Integer(12)
        );
        assert_eq!(dec("12.5").coerce_to(&DataType::Integer), dec("12.5"));

        // Anything becomes text
        assert_eq!(
            dec("29.85").coerce_to(&DataType::String),
            Value::String("29.85".into())
        );
        assert_eq!(
            Value::Boolean(true).coerce_to(&DataType::String),
            Value::String("true".into())
        );

        // Text parses into the column type; blank text is NULL
        assert_eq!(
            Value::String(" 1889.5 ".into()).coerce_to(&DataType::Decimal),
            dec("1889.5")
        );
        assert_eq!(
            Value::String(" ".into()).coerce_to(&DataType::Decimal),
            Value::Null
        );
        assert_eq!(
            Value::String("TRUE".into()).coerce_to(&DataType::Boolean),
            Value::Boolean(true)
        );
        assert_eq!(
            Value::String("n/a".into()).coerce_to(&DataType::Integer),
            Value::String("n/a".into())
        );
        assert!(matches!(
            Value::String("2024-01-15".into()).coerce_to(&DataType::Date),
            Value::Date(_)
        ));
        assert_eq!(
            Value::String(r#"{"a":1}"#.into()).coerce_to(&DataType::Json),
            Value::Json(serde_json::json!({"a": 1}))
        );
        assert_eq!(
            Value::Integer(5).coerce_to(&DataType::Json),
            Value::Json(serde_json::json!(5))
        );

        // NULL fits everywhere
        assert_eq!(Value::Null.coerce_to(&DataType::Integer), Value::Null);
    }

    #[test]
    fn test_header_only_keeps_columns() {
        let order = vec!["id".to_string(), "note".to_string()];
        let schema = SchemaInferer::infer_from_rows_ordered(&[], &order).unwrap();
        let names: Vec<&str> = schema.columns.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(names, ["id", "note"]);
        assert!(schema
            .columns
            .iter()
            .all(|c| c.data_type == DataType::String && c.nullable));
    }

    #[test]
    fn test_schema_file_nullable_defaults_to_true() {
        let file: SchemaFile =
            serde_yaml::from_str("columns:\n  - name: id\n    type: Integer\n").unwrap();
        file.validate().unwrap();
        assert!(file.columns[0].nullable);
    }

    #[test]
    fn test_blank_text_does_not_decide_column_type() {
        let rows: Vec<Row> = ["29.85", " ", "84"]
            .iter()
            .map(|v| {
                let value = match *v {
                    " " => Value::String(" ".into()),
                    "84" => Value::Integer(84),
                    _ => Value::Decimal(v.parse().unwrap()),
                };
                HashMap::from([("total".to_string(), value)])
            })
            .collect();
        let schema = SchemaInferer::infer_from_rows(&rows).unwrap();
        assert_eq!(schema.columns[0].data_type, DataType::Decimal);

        // A column of nothing but blanks stays text
        let rows = vec![HashMap::from([(
            "x".to_string(),
            Value::String(" ".into()),
        )])];
        let schema = SchemaInferer::infer_from_rows(&rows).unwrap();
        assert_eq!(schema.columns[0].data_type, DataType::String);
    }

    #[test]
    fn test_coerce_row() {
        let schema = Schema {
            columns: vec![
                Column {
                    name: "charge".into(),
                    data_type: DataType::Decimal,
                    nullable: true,
                },
                Column {
                    name: "note".into(),
                    data_type: DataType::String,
                    nullable: true,
                },
            ],
            estimated_rows: None,
            primary_key_candidate: None,
        };
        let mut row: Row = HashMap::new();
        row.insert("charge".into(), Value::Integer(20));
        row.insert("note".into(), Value::Integer(7));
        row.insert("extra".into(), Value::Integer(1)); // not in the schema: untouched
        coerce_row(&mut row, &schema);
        assert_eq!(row["charge"], Value::Decimal(Decimal::from(20)));
        assert_eq!(row["note"], Value::String("7".into()));
        assert_eq!(row["extra"], Value::Integer(1));
    }

    #[test]
    fn test_large_schema_inference() {
        let mut rows = Vec::new();
        for i in 0..1000 {
            let mut row = HashMap::new();
            row.insert("id".to_string(), Value::Integer(i));
            row.insert("name".to_string(), Value::String(format!("user_{}", i)));
            if i % 10 == 0 {
                row.insert("optional".to_string(), Value::Null);
            } else {
                row.insert("optional".to_string(), Value::String("present".to_string()));
            }
            rows.push(row);
        }

        let schema = SchemaInferer::infer_from_rows(&rows).unwrap();
        assert_eq!(schema.columns.len(), 3);
        assert_eq!(schema.estimated_rows, Some(1000));

        let optional_col = schema
            .columns
            .iter()
            .find(|c| c.name == "optional")
            .unwrap();
        assert!(optional_col.nullable);
    }

    #[test]
    fn test_missing_columns_in_rows() {
        // Test case where some rows don't have all columns
        let mut row1 = HashMap::new();
        row1.insert("id".to_string(), Value::Integer(1));
        row1.insert("name".to_string(), Value::String("Alice".to_string()));
        row1.insert(
            "email".to_string(),
            Value::String("alice@example.com".to_string()),
        );

        let mut row2 = HashMap::new();
        row2.insert("id".to_string(), Value::Integer(2));
        row2.insert("name".to_string(), Value::String("Bob".to_string()));
        // Missing email column in this row

        let schema = SchemaInferer::infer_from_rows(&[row1, row2]).unwrap();
        assert_eq!(schema.columns.len(), 3);

        let email_col = schema.columns.iter().find(|c| c.name == "email").unwrap();
        assert_eq!(email_col.data_type, DataType::String);
        assert!(email_col.nullable); // Should be nullable because it's missing in row2
    }

    #[test]
    fn test_json_type_inference() {
        let mut row = HashMap::new();
        row.insert("id".to_string(), Value::Integer(1));
        row.insert(
            "metadata".to_string(),
            Value::Json(serde_json::json!({
                "key": "value",
                "count": 42
            })),
        );

        let schema = SchemaInferer::infer_from_rows(&[row]).unwrap();
        assert_eq!(schema.columns.len(), 2);

        let metadata_col = schema
            .columns
            .iter()
            .find(|c| c.name == "metadata")
            .unwrap();
        assert_eq!(metadata_col.data_type, DataType::Json);
        assert!(metadata_col.nullable);
    }

    #[test]
    fn test_json_value_conversion() {
        let json_value = Value::Json(serde_json::json!({"name": "test", "count": 123}));

        // Test arrow_type
        assert_eq!(json_value.arrow_type(), ArrowDataType::Utf8);

        // Test to_string_for_arrow
        let json_str = json_value.to_string_for_arrow().unwrap();
        assert!(json_str.contains("\"name\""));
        assert!(json_str.contains("\"test\""));

        // Test to_json
        assert!(json_value.to_json().is_some());
    }

    #[test]
    fn test_json_default_value() {
        let schema_file = SchemaFile {
            columns: vec![SchemaFileColumn {
                name: "config".to_string(),
                data_type: "json".to_string(),
                nullable: false,
                pattern: None,
                default: Some(r#"{"enabled": true, "count": 0}"#.to_string()),
            }],
        };

        let default = schema_file
            .parse_default_value(r#"{"enabled": true, "count": 0}"#, "json")
            .unwrap();

        match default {
            Value::Json(j) => {
                assert_eq!(j["enabled"], true);
                assert_eq!(j["count"], 0);
            }
            _ => panic!("Expected JSON value"),
        }
    }
}