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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use crate::data_type::{ByteArray, DataType, FixedLenByteArray, Int96};
// TODO: clean up imports (best done when there are few moving parts)
use arrow::array::{
    Array, ArrayRef, BinaryBuilder, DecimalBuilder, FixedSizeBinaryBuilder,
    IntervalDayTimeArray, IntervalDayTimeBuilder, IntervalYearMonthArray,
    IntervalYearMonthBuilder, LargeBinaryBuilder, LargeStringBuilder, PrimitiveBuilder,
    PrimitiveDictionaryBuilder, StringBuilder, StringDictionaryBuilder,
};
use arrow::compute::cast;
use std::convert::{From, TryInto};
use std::sync::Arc;

use crate::errors::Result;
use arrow::datatypes::{ArrowDictionaryKeyType, ArrowPrimitiveType};

use arrow::array::{
    BinaryArray, DecimalArray, DictionaryArray, FixedSizeBinaryArray, LargeBinaryArray,
    LargeStringArray, PrimitiveArray, StringArray, TimestampNanosecondArray,
};
use std::marker::PhantomData;

use crate::data_type::Int32Type as ParquetInt32Type;
use arrow::datatypes::Int32Type;

/// A converter is used to consume record reader's content and convert it to arrow
/// primitive array.
pub trait Converter<S, T> {
    /// This method converts record reader's buffered content into arrow array.
    /// It will consume record reader's data, but will not reset record reader's
    /// state.
    fn convert(&self, source: S) -> Result<T>;
}

pub struct FixedSizeArrayConverter {
    byte_width: i32,
}

impl FixedSizeArrayConverter {
    pub fn new(byte_width: i32) -> Self {
        Self { byte_width }
    }
}

impl Converter<Vec<Option<FixedLenByteArray>>, FixedSizeBinaryArray>
    for FixedSizeArrayConverter
{
    fn convert(
        &self,
        source: Vec<Option<FixedLenByteArray>>,
    ) -> Result<FixedSizeBinaryArray> {
        let mut builder = FixedSizeBinaryBuilder::new(source.len(), self.byte_width);
        for v in source {
            match v {
                Some(array) => builder.append_value(array.data()),
                None => builder.append_null(),
            }?
        }

        Ok(builder.finish())
    }
}

pub struct DecimalArrayConverter {
    precision: i32,
    scale: i32,
}

impl DecimalArrayConverter {
    pub fn new(precision: i32, scale: i32) -> Self {
        Self { precision, scale }
    }

    fn from_bytes_to_i128(b: &[u8]) -> i128 {
        assert!(b.len() <= 16, "DecimalArray supports only up to size 16");
        let first_bit = b[0] & 128u8 == 128u8;
        let mut result = if first_bit { [255u8; 16] } else { [0u8; 16] };
        for (i, v) in b.iter().enumerate() {
            result[i + (16 - b.len())] = *v;
        }
        i128::from_be_bytes(result)
    }
}

impl Converter<Vec<Option<FixedLenByteArray>>, DecimalArray> for DecimalArrayConverter {
    fn convert(&self, source: Vec<Option<FixedLenByteArray>>) -> Result<DecimalArray> {
        let mut builder = DecimalBuilder::new(
            source.len(),
            self.precision as usize,
            self.scale as usize,
        );
        for v in source {
            match v {
                Some(array) => {
                    builder.append_value(Self::from_bytes_to_i128(array.data()))
                }
                None => builder.append_null(),
            }?
        }

        Ok(builder.finish())
    }
}
/// An Arrow Interval converter, which reads the first 4 bytes of a Parquet interval,
/// and interprets it as an i32 value representing the Arrow YearMonth value
pub struct IntervalYearMonthArrayConverter {}

impl Converter<Vec<Option<FixedLenByteArray>>, IntervalYearMonthArray>
    for IntervalYearMonthArrayConverter
{
    fn convert(
        &self,
        source: Vec<Option<FixedLenByteArray>>,
    ) -> Result<IntervalYearMonthArray> {
        let mut builder = IntervalYearMonthBuilder::new(source.len());
        for v in source {
            match v {
                Some(array) => builder.append_value(i32::from_le_bytes(
                    array.data()[0..4].try_into().unwrap(),
                )),
                None => builder.append_null(),
            }?
        }

        Ok(builder.finish())
    }
}

/// An Arrow Interval converter, which reads the last 8 bytes of a Parquet interval,
/// and interprets it as an i32 value representing the Arrow DayTime value
pub struct IntervalDayTimeArrayConverter {}

impl Converter<Vec<Option<FixedLenByteArray>>, IntervalDayTimeArray>
    for IntervalDayTimeArrayConverter
{
    fn convert(
        &self,
        source: Vec<Option<FixedLenByteArray>>,
    ) -> Result<IntervalDayTimeArray> {
        let mut builder = IntervalDayTimeBuilder::new(source.len());
        for v in source {
            match v {
                Some(array) => builder.append_value(i64::from_le_bytes(
                    array.data()[4..12].try_into().unwrap(),
                )),
                None => builder.append_null(),
            }?
        }

        Ok(builder.finish())
    }
}

pub struct Int96ArrayConverter {
    pub timezone: Option<String>,
}

impl Converter<Vec<Option<Int96>>, TimestampNanosecondArray> for Int96ArrayConverter {
    fn convert(&self, source: Vec<Option<Int96>>) -> Result<TimestampNanosecondArray> {
        Ok(TimestampNanosecondArray::from_opt_vec(
            source
                .into_iter()
                .map(|int96| int96.map(|val| val.to_i64() * 1_000_000))
                .collect(),
            self.timezone.clone(),
        ))
    }
}

pub struct Utf8ArrayConverter {}

impl Converter<Vec<Option<ByteArray>>, StringArray> for Utf8ArrayConverter {
    fn convert(&self, source: Vec<Option<ByteArray>>) -> Result<StringArray> {
        let data_size = source
            .iter()
            .map(|x| x.as_ref().map(|b| b.len()).unwrap_or(0))
            .sum();

        let mut builder = StringBuilder::with_capacity(source.len(), data_size);
        for v in source {
            match v {
                Some(array) => builder.append_value(array.as_utf8()?),
                None => builder.append_null(),
            }?
        }

        Ok(builder.finish())
    }
}

pub struct LargeUtf8ArrayConverter {}

impl Converter<Vec<Option<ByteArray>>, LargeStringArray> for LargeUtf8ArrayConverter {
    fn convert(&self, source: Vec<Option<ByteArray>>) -> Result<LargeStringArray> {
        let data_size = source
            .iter()
            .map(|x| x.as_ref().map(|b| b.len()).unwrap_or(0))
            .sum();

        let mut builder = LargeStringBuilder::with_capacity(source.len(), data_size);
        for v in source {
            match v {
                Some(array) => builder.append_value(array.as_utf8()?),
                None => builder.append_null(),
            }?
        }

        Ok(builder.finish())
    }
}

pub struct BinaryArrayConverter {}

impl Converter<Vec<Option<ByteArray>>, BinaryArray> for BinaryArrayConverter {
    fn convert(&self, source: Vec<Option<ByteArray>>) -> Result<BinaryArray> {
        let mut builder = BinaryBuilder::new(source.len());
        for v in source {
            match v {
                Some(array) => builder.append_value(array.data()),
                None => builder.append_null(),
            }?
        }

        Ok(builder.finish())
    }
}

pub struct LargeBinaryArrayConverter {}

impl Converter<Vec<Option<ByteArray>>, LargeBinaryArray> for LargeBinaryArrayConverter {
    fn convert(&self, source: Vec<Option<ByteArray>>) -> Result<LargeBinaryArray> {
        let mut builder = LargeBinaryBuilder::new(source.len());
        for v in source {
            match v {
                Some(array) => builder.append_value(array.data()),
                None => builder.append_null(),
            }?
        }

        Ok(builder.finish())
    }
}

pub struct StringDictionaryArrayConverter {}

impl<K: ArrowDictionaryKeyType> Converter<Vec<Option<ByteArray>>, DictionaryArray<K>>
    for StringDictionaryArrayConverter
{
    fn convert(&self, source: Vec<Option<ByteArray>>) -> Result<DictionaryArray<K>> {
        let data_size = source
            .iter()
            .map(|x| x.as_ref().map(|b| b.len()).unwrap_or(0))
            .sum();

        let keys_builder = PrimitiveBuilder::<K>::new(source.len());
        let values_builder = StringBuilder::with_capacity(source.len(), data_size);

        let mut builder = StringDictionaryBuilder::new(keys_builder, values_builder);
        for v in source {
            match v {
                Some(array) => {
                    let _ = builder.append(array.as_utf8()?)?;
                }
                None => builder.append_null()?,
            }
        }

        Ok(builder.finish())
    }
}

pub struct DictionaryArrayConverter<DictValueSourceType, DictValueTargetType, ParquetType>
{
    _dict_value_source_marker: PhantomData<DictValueSourceType>,
    _dict_value_target_marker: PhantomData<DictValueTargetType>,
    _parquet_marker: PhantomData<ParquetType>,
}

impl<DictValueSourceType, DictValueTargetType, ParquetType>
    DictionaryArrayConverter<DictValueSourceType, DictValueTargetType, ParquetType>
{
    pub fn new() -> Self {
        Self {
            _dict_value_source_marker: PhantomData,
            _dict_value_target_marker: PhantomData,
            _parquet_marker: PhantomData,
        }
    }
}

impl<K, DictValueSourceType, DictValueTargetType, ParquetType>
    Converter<Vec<Option<<ParquetType as DataType>::T>>, DictionaryArray<K>>
    for DictionaryArrayConverter<DictValueSourceType, DictValueTargetType, ParquetType>
where
    K: ArrowPrimitiveType,
    DictValueSourceType: ArrowPrimitiveType,
    DictValueTargetType: ArrowPrimitiveType,
    ParquetType: DataType,
    PrimitiveArray<DictValueSourceType>: From<Vec<Option<<ParquetType as DataType>::T>>>,
{
    fn convert(
        &self,
        source: Vec<Option<<ParquetType as DataType>::T>>,
    ) -> Result<DictionaryArray<K>> {
        let keys_builder = PrimitiveBuilder::<K>::new(source.len());
        let values_builder = PrimitiveBuilder::<DictValueTargetType>::new(source.len());

        let mut builder = PrimitiveDictionaryBuilder::new(keys_builder, values_builder);

        let source_array: Arc<dyn Array> =
            Arc::new(PrimitiveArray::<DictValueSourceType>::from(source));
        let target_array = cast(&source_array, &DictValueTargetType::DATA_TYPE)?;
        let target = target_array
            .as_any()
            .downcast_ref::<PrimitiveArray<DictValueTargetType>>()
            .unwrap();

        for i in 0..target.len() {
            if target.is_null(i) {
                builder.append_null()?;
            } else {
                let _ = builder.append(target.value(i))?;
            }
        }

        Ok(builder.finish())
    }
}

pub type Utf8Converter =
    ArrayRefConverter<Vec<Option<ByteArray>>, StringArray, Utf8ArrayConverter>;
pub type LargeUtf8Converter =
    ArrayRefConverter<Vec<Option<ByteArray>>, LargeStringArray, LargeUtf8ArrayConverter>;
pub type BinaryConverter =
    ArrayRefConverter<Vec<Option<ByteArray>>, BinaryArray, BinaryArrayConverter>;
pub type LargeBinaryConverter = ArrayRefConverter<
    Vec<Option<ByteArray>>,
    LargeBinaryArray,
    LargeBinaryArrayConverter,
>;
pub type StringDictionaryConverter<T> = ArrayRefConverter<
    Vec<Option<ByteArray>>,
    DictionaryArray<T>,
    StringDictionaryArrayConverter,
>;
pub type DictionaryConverter<K, SV, TV, P> = ArrayRefConverter<
    Vec<Option<<P as DataType>::T>>,
    DictionaryArray<K>,
    DictionaryArrayConverter<SV, TV, P>,
>;
pub type PrimitiveDictionaryConverter<K, V> = ArrayRefConverter<
    Vec<Option<<ParquetInt32Type as DataType>::T>>,
    DictionaryArray<K>,
    DictionaryArrayConverter<Int32Type, V, ParquetInt32Type>,
>;

pub type Int96Converter =
    ArrayRefConverter<Vec<Option<Int96>>, TimestampNanosecondArray, Int96ArrayConverter>;

pub type FixedLenBinaryConverter = ArrayRefConverter<
    Vec<Option<FixedLenByteArray>>,
    FixedSizeBinaryArray,
    FixedSizeArrayConverter,
>;
pub type IntervalYearMonthConverter = ArrayRefConverter<
    Vec<Option<FixedLenByteArray>>,
    IntervalYearMonthArray,
    IntervalYearMonthArrayConverter,
>;
pub type IntervalDayTimeConverter = ArrayRefConverter<
    Vec<Option<FixedLenByteArray>>,
    IntervalDayTimeArray,
    IntervalDayTimeArrayConverter,
>;

pub type DecimalConverter = ArrayRefConverter<
    Vec<Option<FixedLenByteArray>>,
    DecimalArray,
    DecimalArrayConverter,
>;

pub struct FromConverter<S, T> {
    _source: PhantomData<S>,
    _dest: PhantomData<T>,
}

impl<S, T> FromConverter<S, T>
where
    T: From<S>,
{
    pub fn new() -> Self {
        Self {
            _source: PhantomData,
            _dest: PhantomData,
        }
    }
}

impl<S, T> Converter<S, T> for FromConverter<S, T>
where
    T: From<S>,
{
    fn convert(&self, source: S) -> Result<T> {
        Ok(T::from(source))
    }
}

pub struct ArrayRefConverter<S, A, C> {
    _source: PhantomData<S>,
    _array: PhantomData<A>,
    converter: C,
}

impl<S, A, C> ArrayRefConverter<S, A, C>
where
    A: Array + 'static,
    C: Converter<S, A> + 'static,
{
    pub fn new(converter: C) -> Self {
        Self {
            _source: PhantomData,
            _array: PhantomData,
            converter,
        }
    }
}

impl<S, A, C> Converter<S, ArrayRef> for ArrayRefConverter<S, A, C>
where
    A: Array + 'static,
    C: Converter<S, A> + 'static,
{
    fn convert(&self, source: S) -> Result<ArrayRef> {
        self.converter
            .convert(source)
            .map(|array| Arc::new(array) as ArrayRef)
    }
}