copybook-arrow 0.4.3

COBOL schema conversion to Apache Arrow and Parquet formats.
Documentation
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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Column accumulator implementations for building Arrow arrays from raw COBOL data.
//!
//! Each accumulator type wraps an Arrow builder and knows how to extract a typed
//! value from a raw byte slice using the appropriate codec function.

use arrow::array::{
    ArrayRef, Decimal128Builder, Float32Builder, Float64Builder, PrimitiveBuilder, StringBuilder,
};
use arrow::datatypes::{Int16Type, Int32Type, Int64Type, UInt16Type, UInt32Type, UInt64Type};
use std::sync::Arc;

use copybook_codec::Codepage;
use copybook_codec::FloatFormat;
use copybook_codec::UnmappablePolicy;
use copybook_codec::charset::ebcdic_to_utf8;
use copybook_codec::numeric::{
    decode_binary_int, decode_float_double_with_format, decode_float_single_with_format,
    decode_packed_decimal, decode_zoned_decimal,
};
use copybook_core::schema::FieldKind;

use crate::options::ArrowOptions;
use crate::{ArrowError, Result};

/// Trait for accumulating values into Arrow arrays.
pub(crate) trait ColumnAccumulator: Send {
    /// Append a value from raw binary data for this field.
    fn append_value(&mut self, data: &[u8]) -> Result<()>;

    /// Append a null value.
    fn append_null(&mut self);

    /// Finish building and return the Arrow array.
    fn finish(&mut self) -> ArrayRef;

    /// Number of values accumulated.
    #[allow(dead_code)]
    fn len(&self) -> usize;
}

/// Create the right accumulator for a given `FieldKind`.
pub(crate) fn create_accumulator(
    kind: &FieldKind,
    field_len: u32,
    options: &ArrowOptions,
) -> Result<Box<dyn ColumnAccumulator>> {
    match kind {
        FieldKind::Alphanum { .. } => {
            Ok(Box::new(Utf8Accumulator::new(options.codepage, field_len)))
        }

        FieldKind::ZonedDecimal {
            digits,
            scale,
            signed,
            ..
        } => Ok(Box::new(ZonedDecimalAccumulator::new(
            *digits,
            *scale,
            *signed,
            options.codepage,
        ))),

        FieldKind::PackedDecimal {
            digits,
            scale,
            signed,
        } => Ok(Box::new(PackedDecimalAccumulator::new(
            *digits, *scale, *signed,
        ))),

        FieldKind::BinaryInt { bits, signed } => make_int_accumulator(*bits, *signed),

        FieldKind::FloatSingle => Ok(Box::new(Float32Accumulator::new(options.float_format))),
        FieldKind::FloatDouble => Ok(Box::new(Float64Accumulator::new(options.float_format))),

        FieldKind::EditedNumeric { .. } => {
            // For now, edited numeric fields are stored as Utf8 strings
            Ok(Box::new(Utf8Accumulator::new(options.codepage, field_len)))
        }

        _ => Err(ArrowError::ColumnBuild(format!(
            "No accumulator for field kind: {kind:?}"
        ))),
    }
}

// ---------------------------------------------------------------------------
// Utf8Accumulator
// ---------------------------------------------------------------------------

struct Utf8Accumulator {
    builder: StringBuilder,
    codepage: Codepage,
    field_len: u32,
    count: usize,
}

impl Utf8Accumulator {
    fn new(codepage: Codepage, field_len: u32) -> Self {
        Self {
            builder: StringBuilder::new(),
            codepage,
            field_len,
            count: 0,
        }
    }
}

impl ColumnAccumulator for Utf8Accumulator {
    fn append_value(&mut self, data: &[u8]) -> Result<()> {
        let len = self.field_len as usize;
        let slice = if data.len() >= len {
            &data[..len]
        } else {
            data
        };
        let s = ebcdic_to_utf8(slice, self.codepage, UnmappablePolicy::Replace)
            .map_err(|e| ArrowError::Codec(e.to_string()))?;
        // Trim trailing spaces (COBOL convention)
        let trimmed = s.trim_end();
        self.builder.append_value(trimmed);
        self.count += 1;
        Ok(())
    }

    fn append_null(&mut self) {
        self.builder.append_null();
        self.count += 1;
    }

    fn finish(&mut self) -> ArrayRef {
        Arc::new(self.builder.finish())
    }

    fn len(&self) -> usize {
        self.count
    }
}

// ---------------------------------------------------------------------------
// ZonedDecimalAccumulator
// ---------------------------------------------------------------------------

struct ZonedDecimalAccumulator {
    builder: Decimal128Builder,
    digits: u16,
    scale: i16,
    signed: bool,
    codepage: Codepage,
    count: usize,
}

impl ZonedDecimalAccumulator {
    fn new(digits: u16, scale: i16, signed: bool, codepage: Codepage) -> Self {
        let precision = u8::try_from(digits).unwrap_or(u8::MAX);
        let arrow_scale = i8::try_from(scale).unwrap_or(0);
        Self {
            builder: Decimal128Builder::new()
                .with_precision_and_scale(precision, arrow_scale)
                .unwrap_or_else(|_| Decimal128Builder::new()),
            digits,
            scale,
            signed,
            codepage,
            count: 0,
        }
    }
}

impl ColumnAccumulator for ZonedDecimalAccumulator {
    fn append_value(&mut self, data: &[u8]) -> Result<()> {
        let len = usize::from(self.digits);
        let slice = if data.len() >= len {
            &data[..len]
        } else {
            data
        };
        let sd = decode_zoned_decimal(
            slice,
            self.digits,
            self.scale,
            self.signed,
            self.codepage,
            false,
        )
        .map_err(|e| ArrowError::Codec(e.to_string()))?;
        let i128_val = small_decimal_to_i128(&sd);
        self.builder.append_value(i128_val);
        self.count += 1;
        Ok(())
    }

    fn append_null(&mut self) {
        self.builder.append_null();
        self.count += 1;
    }

    fn finish(&mut self) -> ArrayRef {
        Arc::new(self.builder.finish())
    }

    fn len(&self) -> usize {
        self.count
    }
}

// ---------------------------------------------------------------------------
// PackedDecimalAccumulator
// ---------------------------------------------------------------------------

struct PackedDecimalAccumulator {
    builder: Decimal128Builder,
    digits: u16,
    scale: i16,
    signed: bool,
    count: usize,
}

impl PackedDecimalAccumulator {
    fn new(digits: u16, scale: i16, signed: bool) -> Self {
        let precision = u8::try_from(digits).unwrap_or(u8::MAX);
        let arrow_scale = i8::try_from(scale).unwrap_or(0);
        Self {
            builder: Decimal128Builder::new()
                .with_precision_and_scale(precision, arrow_scale)
                .unwrap_or_else(|_| Decimal128Builder::new()),
            digits,
            scale,
            signed,
            count: 0,
        }
    }
}

impl ColumnAccumulator for PackedDecimalAccumulator {
    fn append_value(&mut self, data: &[u8]) -> Result<()> {
        let expected_bytes = usize::from((self.digits + 1).div_ceil(2));
        let slice = if data.len() >= expected_bytes {
            &data[..expected_bytes]
        } else {
            data
        };
        let sd = decode_packed_decimal(slice, self.digits, self.scale, self.signed)
            .map_err(|e| ArrowError::Codec(e.to_string()))?;
        let i128_val = small_decimal_to_i128(&sd);
        self.builder.append_value(i128_val);
        self.count += 1;
        Ok(())
    }

    fn append_null(&mut self) {
        self.builder.append_null();
        self.count += 1;
    }

    fn finish(&mut self) -> ArrayRef {
        Arc::new(self.builder.finish())
    }

    fn len(&self) -> usize {
        self.count
    }
}

// ---------------------------------------------------------------------------
// Integer accumulators
// ---------------------------------------------------------------------------

fn make_int_accumulator(bits: u16, signed: bool) -> Result<Box<dyn ColumnAccumulator>> {
    match (bits, signed) {
        (16, true) => Ok(Box::new(IntAccumulator::<Int16Type>::new(16, true))),
        (16, false) => Ok(Box::new(IntAccumulator::<UInt16Type>::new(16, false))),
        (32, true) => Ok(Box::new(IntAccumulator::<Int32Type>::new(32, true))),
        (32, false) => Ok(Box::new(IntAccumulator::<UInt32Type>::new(32, false))),
        (64, true) => Ok(Box::new(IntAccumulator::<Int64Type>::new(64, true))),
        (64, false) => Ok(Box::new(IntAccumulator::<UInt64Type>::new(64, false))),
        _ => Err(ArrowError::ColumnBuild(format!(
            "Unsupported binary int width: {bits}"
        ))),
    }
}

struct IntAccumulator<T: arrow::datatypes::ArrowPrimitiveType> {
    builder: PrimitiveBuilder<T>,
    bits: u16,
    signed: bool,
    count: usize,
}

impl<T: arrow::datatypes::ArrowPrimitiveType> IntAccumulator<T> {
    fn new(bits: u16, signed: bool) -> Self {
        Self {
            builder: PrimitiveBuilder::<T>::new(),
            bits,
            signed,
            count: 0,
        }
    }
}

macro_rules! impl_int_accumulator {
    ($arrow_ty:ty, $native_ty:ty) => {
        impl ColumnAccumulator for IntAccumulator<$arrow_ty> {
            #[allow(
                clippy::cast_possible_truncation,
                clippy::cast_sign_loss,
                clippy::cast_possible_wrap
            )]
            fn append_value(&mut self, data: &[u8]) -> Result<()> {
                let byte_len = usize::from(self.bits / 8);
                let slice = if data.len() >= byte_len {
                    &data[..byte_len]
                } else {
                    data
                };
                let val = decode_binary_int(slice, self.bits, self.signed)
                    .map_err(|e| ArrowError::Codec(e.to_string()))?;
                self.builder.append_value(val as $native_ty);
                self.count += 1;
                Ok(())
            }

            fn append_null(&mut self) {
                self.builder.append_null();
                self.count += 1;
            }

            fn finish(&mut self) -> ArrayRef {
                Arc::new(self.builder.finish())
            }

            fn len(&self) -> usize {
                self.count
            }
        }
    };
}

impl_int_accumulator!(Int16Type, i16);
impl_int_accumulator!(UInt16Type, u16);
impl_int_accumulator!(Int32Type, i32);
impl_int_accumulator!(UInt32Type, u32);
impl_int_accumulator!(Int64Type, i64);
impl_int_accumulator!(UInt64Type, u64);

// ---------------------------------------------------------------------------
// Float accumulators
// ---------------------------------------------------------------------------

struct Float32Accumulator {
    builder: Float32Builder,
    float_format: FloatFormat,
    count: usize,
}

impl Float32Accumulator {
    fn new(float_format: FloatFormat) -> Self {
        Self {
            builder: Float32Builder::new(),
            float_format,
            count: 0,
        }
    }
}

impl ColumnAccumulator for Float32Accumulator {
    fn append_value(&mut self, data: &[u8]) -> Result<()> {
        if data.len() < 4 {
            self.builder.append_null();
        } else {
            let val = decode_float_single_with_format(data, self.float_format)
                .map_err(|e| ArrowError::Codec(e.to_string()))?;
            if val.is_nan() || val.is_infinite() {
                self.builder.append_null();
            } else {
                self.builder.append_value(val);
            }
        }
        self.count += 1;
        Ok(())
    }

    fn append_null(&mut self) {
        self.builder.append_null();
        self.count += 1;
    }

    fn finish(&mut self) -> ArrayRef {
        Arc::new(self.builder.finish())
    }

    fn len(&self) -> usize {
        self.count
    }
}

struct Float64Accumulator {
    builder: Float64Builder,
    float_format: FloatFormat,
    count: usize,
}

impl Float64Accumulator {
    fn new(float_format: FloatFormat) -> Self {
        Self {
            builder: Float64Builder::new(),
            float_format,
            count: 0,
        }
    }
}

impl ColumnAccumulator for Float64Accumulator {
    fn append_value(&mut self, data: &[u8]) -> Result<()> {
        if data.len() < 8 {
            self.builder.append_null();
        } else {
            let val = decode_float_double_with_format(data, self.float_format)
                .map_err(|e| ArrowError::Codec(e.to_string()))?;
            if val.is_nan() || val.is_infinite() {
                self.builder.append_null();
            } else {
                self.builder.append_value(val);
            }
        }
        self.count += 1;
        Ok(())
    }

    fn append_null(&mut self) {
        self.builder.append_null();
        self.count += 1;
    }

    fn finish(&mut self) -> ArrayRef {
        Arc::new(self.builder.finish())
    }

    fn len(&self) -> usize {
        self.count
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Convert a [`SmallDecimal`](copybook_codec::SmallDecimal) to an `i128` value
/// suitable for Arrow `Decimal128`.
///
/// `SmallDecimal` stores `value` (unscaled `i64`) and `negative` flag.
/// Arrow `Decimal128` stores the unscaled integer as `i128`.
fn small_decimal_to_i128(sd: &copybook_codec::SmallDecimal) -> i128 {
    let abs = i128::from(sd.value);
    if sd.negative { -abs } else { abs }
}