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
use datafusion::arrow::{
    array::{Array, RecordBatch},
    compute::cast,
    datatypes::{DataType, IntervalUnit, SchemaRef},
};
use std::sync::Arc;

use super::{
    intervals_cast::{
        cast_interval_monthdaynano_to_daytime, cast_interval_monthdaynano_to_yearmonth,
    },
    lists_cast::{cast_string_to_fixed_size_list, cast_string_to_large_list, cast_string_to_list},
    struct_cast::cast_string_to_struct,
};

pub type Result<T, E = Error> = std::result::Result<T, E>;

#[derive(Debug)]
pub enum Error {
    UnableToConvertRecordBatch {
        source: datafusion::arrow::error::ArrowError,
    },

    UnexpectedNumberOfColumns {
        expected: usize,
        found: usize,
    },
}

impl std::error::Error for Error {}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Error::UnableToConvertRecordBatch { source } => {
                write!(f, "Unable to convert record batch: {}", source)
            }
            Error::UnexpectedNumberOfColumns { expected, found } => {
                write!(
                    f,
                    "Unexpected number of columns. Expected: {}, Found: {}",
                    expected, found
                )
            }
        }
    }
}

/// Cast a given record batch into a new record batch with the given schema.
/// It assumes the record batch columns are correctly ordered.
#[allow(clippy::needless_pass_by_value)]
pub fn try_cast_to(record_batch: RecordBatch, expected_schema: SchemaRef) -> Result<RecordBatch> {
    let actual_schema = record_batch.schema();

    if actual_schema.fields().len() != expected_schema.fields().len() {
        return Err(Error::UnexpectedNumberOfColumns {
            expected: expected_schema.fields().len(),
            found: actual_schema.fields().len(),
        });
    }

    let cols = expected_schema
        .fields()
        .iter()
        .enumerate()
        .map(|(i, expected_field)| {
            let record_batch_col = record_batch.column(i);

            match (record_batch_col.data_type(), expected_field.data_type()) {
                (DataType::Utf8, DataType::List(item_type)) => {
                    cast_string_to_list(&Arc::clone(record_batch_col), item_type)
                        .map_err(|e| Error::UnableToConvertRecordBatch { source: e })
                }
                (DataType::Utf8, DataType::LargeList(item_type)) => {
                    cast_string_to_large_list(&Arc::clone(record_batch_col), item_type)
                        .map_err(|e| Error::UnableToConvertRecordBatch { source: e })
                }
                (DataType::Utf8, DataType::FixedSizeList(item_type, value_length)) => {
                    cast_string_to_fixed_size_list(
                        &Arc::clone(record_batch_col),
                        item_type,
                        *value_length,
                    )
                    .map_err(|e| Error::UnableToConvertRecordBatch { source: e })
                }
                (DataType::Utf8, DataType::Struct(_)) => {
                    cast_string_to_struct(&Arc::clone(record_batch_col), expected_field.clone())
                        .map_err(|e| Error::UnableToConvertRecordBatch { source: e })
                }
                (
                    DataType::Interval(IntervalUnit::MonthDayNano),
                    DataType::Interval(IntervalUnit::YearMonth),
                ) => cast_interval_monthdaynano_to_yearmonth(&Arc::clone(record_batch_col))
                    .map_err(|e| Error::UnableToConvertRecordBatch { source: e }),
                (
                    DataType::Interval(IntervalUnit::MonthDayNano),
                    DataType::Interval(IntervalUnit::DayTime),
                ) => cast_interval_monthdaynano_to_daytime(&Arc::clone(record_batch_col))
                    .map_err(|e| Error::UnableToConvertRecordBatch { source: e }),
                _ => cast(&Arc::clone(record_batch_col), expected_field.data_type())
                    .map_err(|e| Error::UnableToConvertRecordBatch { source: e }),
            }
        })
        .collect::<Result<Vec<Arc<dyn Array>>>>()?;

    RecordBatch::try_new(expected_schema, cols)
        .map_err(|e| Error::UnableToConvertRecordBatch { source: e })
}

#[cfg(test)]
mod test {
    use datafusion::arrow::{
        array::{Int32Array, StringArray},
        datatypes::{DataType, Field, Schema, TimeUnit},
    };

    use super::*;

    fn schema() -> SchemaRef {
        Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int32, false),
            Field::new("b", DataType::Utf8, false),
            Field::new("c", DataType::Utf8, false),
        ]))
    }

    fn to_schema() -> SchemaRef {
        Arc::new(Schema::new(vec![
            Field::new("a", DataType::Int64, false),
            Field::new("b", DataType::LargeUtf8, false),
            Field::new("c", DataType::Timestamp(TimeUnit::Microsecond, None), false),
        ]))
    }

    fn batch_input() -> RecordBatch {
        RecordBatch::try_new(
            schema(),
            vec![
                Arc::new(Int32Array::from(vec![1, 2, 3])),
                Arc::new(StringArray::from(vec!["foo", "bar", "baz"])),
                Arc::new(StringArray::from(vec![
                    "2024-01-13 03:18:09.000000",
                    "2024-01-13 03:18:09",
                    "2024-01-13 03:18:09.000",
                ])),
            ],
        )
        .expect("record batch should not panic")
    }

    #[test]
    fn test_string_to_timestamp_conversion() {
        let result = try_cast_to(batch_input(), to_schema()).expect("converted");
        assert_eq!(3, result.num_rows());
    }
}