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
use arrow::array::{
    TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray,
    TimestampSecondArray,
};
use proof_of_sql_parser::posql_time::PoSQLTimeUnit;
use std::sync::Arc;

/// Extension trait for Vec<T> to convert it to an Arrow array
pub trait ToArrow {
    /// Returns the equivalent Arrow type
    fn to_type(&self) -> arrow::datatypes::DataType;
    /// Converts the Vec<T> to an Arrow `ArrayRef`.
    fn to_array(self) -> Arc<dyn arrow::array::Array>;
}

impl ToArrow for Vec<bool> {
    fn to_type(&self) -> arrow::datatypes::DataType {
        arrow::datatypes::DataType::Boolean
    }

    fn to_array(self) -> Arc<dyn arrow::array::Array> {
        Arc::new(<arrow::array::BooleanArray>::from(self))
    }
}

/// A wrapper around i64 to mitigate conflicting From<i64>
/// implementations
#[derive(Clone)]
pub struct Time {
    /// i64 count of timeunits since unix epoch
    pub timestamp: i64,
    /// Timeunit of this time
    pub unit: PoSQLTimeUnit,
}

impl ToArrow for Vec<Time> {
    fn to_type(&self) -> arrow::datatypes::DataType {
        match self.first().map(|time| time.unit) {
            Some(PoSQLTimeUnit::Second) => {
                arrow::datatypes::DataType::Timestamp(arrow::datatypes::TimeUnit::Second, None)
            }
            Some(PoSQLTimeUnit::Millisecond) => {
                arrow::datatypes::DataType::Timestamp(arrow::datatypes::TimeUnit::Millisecond, None)
            }
            Some(PoSQLTimeUnit::Microsecond) => {
                arrow::datatypes::DataType::Timestamp(arrow::datatypes::TimeUnit::Microsecond, None)
            }
            Some(PoSQLTimeUnit::Nanosecond) => {
                arrow::datatypes::DataType::Timestamp(arrow::datatypes::TimeUnit::Nanosecond, None)
            }
            None => panic!("Empty Vec<Time> cannot determine TimeUnit"),
        }
    }

    fn to_array(self) -> Arc<dyn arrow::array::Array> {
        match self.first().map(|time| time.unit) {
            Some(PoSQLTimeUnit::Second) => {
                let raw_data: Vec<i64> = self.into_iter().map(|time| time.timestamp).collect();
                Arc::new(TimestampSecondArray::from(raw_data))
            }
            Some(PoSQLTimeUnit::Millisecond) => {
                let raw_data: Vec<i64> = self.into_iter().map(|time| time.timestamp).collect();
                Arc::new(TimestampMillisecondArray::from(raw_data))
            }
            Some(PoSQLTimeUnit::Microsecond) => {
                let raw_data: Vec<i64> = self.into_iter().map(|time| time.timestamp).collect();
                Arc::new(TimestampMicrosecondArray::from(raw_data))
            }
            Some(PoSQLTimeUnit::Nanosecond) => {
                let raw_data: Vec<i64> = self.into_iter().map(|time| time.timestamp).collect();
                Arc::new(TimestampNanosecondArray::from(raw_data))
            }
            None => panic!("Empty Vec<Time> cannot determine TimeUnit"),
        }
    }
}

macro_rules! int_to_arrow_array {
    ($tt:ty, $dtt:expr, $att:ty) => {
        impl ToArrow for Vec<$tt> {
            fn to_type(&self) -> arrow::datatypes::DataType {
                $dtt
            }

            fn to_array(self) -> Arc<dyn arrow::array::Array> {
                // this cast normalizes the table as we only support i64 values
                let v = self.iter().map(|v| *v).collect::<Vec<_>>();
                Arc::new(<$att>::from(v))
            }
        }
    };
}

int_to_arrow_array!(
    i16,
    arrow::datatypes::DataType::Int16,
    arrow::array::Int16Array
);

int_to_arrow_array!(
    i32,
    arrow::datatypes::DataType::Int32,
    arrow::array::Int32Array
);

int_to_arrow_array!(
    i64,
    arrow::datatypes::DataType::Int64,
    arrow::array::Int64Array
);

impl ToArrow for Vec<i128> {
    fn to_type(&self) -> arrow::datatypes::DataType {
        arrow::datatypes::DataType::Decimal128(38, 0)
    }

    fn to_array(self) -> Arc<dyn arrow::array::Array> {
        Arc::new(
            arrow::array::Decimal128Array::from(self)
                .with_precision_and_scale(38, 0)
                .unwrap(),
        )
    }
}

macro_rules! string_to_arrow_array {
    ($tt:ty, $dtt:expr, $att:ty) => {
        impl ToArrow for Vec<$tt> {
            fn to_type(&self) -> arrow::datatypes::DataType {
                $dtt
            }

            fn to_array(self) -> Arc<dyn arrow::array::Array> {
                Arc::new(<$att>::from(self))
            }
        }
    };
}

string_to_arrow_array!(
    &str,
    arrow::datatypes::DataType::Utf8,
    arrow::array::StringArray
);
string_to_arrow_array!(
    String,
    arrow::datatypes::DataType::Utf8,
    arrow::array::StringArray
);

/// Utility macro to simplify the creation of RecordBatches
#[macro_export]
macro_rules! record_batch {
    ($($col_name:expr => $slice:expr), + $(,)?) => {
        {
            use std::sync::Arc;
            use arrow::datatypes::Field;
            use arrow::datatypes::Schema;
            use arrow::record_batch::RecordBatch;
            use $crate::base::database::ToArrow;

            let schema = Arc::new(Schema::new(
                vec![$(
                    Field::new(&$col_name.to_string(), $slice.to_vec().to_type(), false)
                ,)+]));

            let arrays = vec![$($slice.to_vec().to_array(),)+];

            RecordBatch::try_new(schema, arrays).unwrap()
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::record_batch;
    use arrow::{
        datatypes::{Field, Schema},
        record_batch::RecordBatch,
    };
    use std::sync::Arc;

    #[test]
    fn test_record_batch_macro() {
        let batch = record_batch!(
            "f" => ["abc", "t", "fg"],
            "ghisi" => [-99_i64, 1230, 222],
            "boolean" => [true, false, true],
        );

        let arrays: Vec<Arc<dyn arrow::array::Array>> = vec![
            Arc::new(arrow::array::StringArray::from(["abc", "t", "fg"].to_vec())),
            Arc::new(arrow::array::Int64Array::from(
                [-99_i64, 1230, 222].to_vec(),
            )),
            Arc::new(arrow::array::BooleanArray::from(
                [true, false, true].to_vec(),
            )),
        ];

        let schema = Arc::new(Schema::new(vec![
            Field::new("f", arrow::datatypes::DataType::Utf8, false),
            Field::new("ghisi", arrow::datatypes::DataType::Int64, false),
            Field::new("boolean", arrow::datatypes::DataType::Boolean, false),
        ]));

        let expected_batch = RecordBatch::try_new(schema, arrays).unwrap();

        assert_eq!(batch, expected_batch);
    }

    #[test]
    fn we_can_create_a_record_batch_with_i128_values() {
        let batch = record_batch!(
            "ghisi" => [-99_i128, 1230, 222, i128::MAX, i128::MIN]
        );

        let arrays: Vec<Arc<dyn arrow::array::Array>> = vec![Arc::new(
            arrow::array::Decimal128Array::from(
                [-99_i128, 1230, 222, i128::MAX, i128::MIN].to_vec(),
            )
            .with_precision_and_scale(38, 0)
            .unwrap(),
        )];

        let schema = Arc::new(Schema::new(vec![Field::new(
            "ghisi",
            arrow::datatypes::DataType::Decimal128(38, 0),
            false,
        )]));

        let expected_batch = RecordBatch::try_new(schema, arrays).unwrap();

        assert_eq!(batch, expected_batch);
    }
}