Skip to main content

common_datasource/file_format/
decimal.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Reads decimal and unsigned integer columns from the text of a csv or json file.
16//!
17//! A file reader that decodes a number into a `Float64` loses the digits a `Float64` can't
18//! hold. Arrow's own decimal decoding is wrong for some numbers in scientific notation, and its
19//! json integer decoding goes through a `Float64` for them. So the readers hand over the text
20//! of such a column and [`parse_number_columns`] parses it.
21
22use std::sync::Arc;
23
24use arrow::array::{Array, ArrayRef, AsArray, Decimal128Array, UInt64Array};
25use arrow::error::ArrowError;
26use arrow::record_batch::RecordBatch;
27use arrow_schema::{DataType, Field, Schema, SchemaRef};
28use datafusion::error::DataFusionError;
29use datafusion::physical_plan::SendableRecordBatchStream;
30use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
31use futures::StreamExt;
32
33/// The type to parse the text of a column into.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum TextNumber {
36    Decimal128 { precision: u8, scale: i8 },
37    UInt64,
38}
39
40impl TextNumber {
41    fn data_type(&self) -> DataType {
42        match self {
43            TextNumber::Decimal128 { precision, scale } => DataType::Decimal128(*precision, *scale),
44            TextNumber::UInt64 => DataType::UInt64,
45        }
46    }
47}
48
49/// Parses the string columns of `stream` that have a type in `numbers` into columns of that
50/// type. `numbers` has one entry for each column of the stream.
51///
52/// With `empty_as_null` an empty string is read as NULL, which is what an empty csv field is
53/// for a number. Without it an empty string is an error, like any other text that is not a
54/// number.
55pub fn parse_number_columns(
56    stream: SendableRecordBatchStream,
57    numbers: Vec<Option<TextNumber>>,
58    empty_as_null: bool,
59) -> SendableRecordBatchStream {
60    if numbers.iter().all(Option::is_none) {
61        return stream;
62    }
63
64    let input_schema = stream.schema();
65    let fields = input_schema
66        .fields()
67        .iter()
68        .zip(&numbers)
69        .map(|(field, number)| match number {
70            Some(number) => Arc::new(Field::clone(field).with_data_type(number.data_type())),
71            None => field.clone(),
72        })
73        .collect::<Vec<_>>();
74    let schema = Arc::new(Schema::new_with_metadata(
75        fields,
76        input_schema.metadata().clone(),
77    ));
78
79    let output_schema = schema.clone();
80    let stream = stream.map(move |batch| {
81        parse_number_batch(&batch?, &output_schema, &numbers, empty_as_null)
82            .map_err(DataFusionError::from)
83    });
84
85    Box::pin(RecordBatchStreamAdapter::new(schema, stream))
86}
87
88fn parse_number_batch(
89    batch: &RecordBatch,
90    schema: &SchemaRef,
91    numbers: &[Option<TextNumber>],
92    empty_as_null: bool,
93) -> Result<RecordBatch, ArrowError> {
94    let columns = batch
95        .columns()
96        .iter()
97        .zip(numbers)
98        .map(|(column, number)| match number {
99            Some(number) => parse_number_array(column, *number, empty_as_null),
100            None => Ok(column.clone()),
101        })
102        .collect::<Result<Vec<_>, _>>()?;
103
104    RecordBatch::try_new(schema.clone(), columns)
105}
106
107fn parse_number_array(
108    array: &ArrayRef,
109    number: TextNumber,
110    empty_as_null: bool,
111) -> Result<ArrayRef, ArrowError> {
112    let strings = array.as_string_opt::<i32>().ok_or_else(|| {
113        ArrowError::CastError(format!(
114            "expected a string column to parse {} from, got {}",
115            number.data_type(),
116            array.data_type()
117        ))
118    })?;
119    let texts = strings
120        .iter()
121        .map(|text| text.filter(|text| !(empty_as_null && text.is_empty())));
122
123    Ok(match number {
124        TextNumber::Decimal128 { precision, scale } => Arc::new(
125            texts
126                .map(|text| {
127                    text.map(|text| parse_decimal128(text, precision, scale))
128                        .transpose()
129                })
130                .collect::<Result<Decimal128Array, _>>()?
131                .with_precision_and_scale(precision, scale)?,
132        ),
133        TextNumber::UInt64 => Arc::new(
134            texts
135                .map(|text| text.map(parse_uint64).transpose())
136                .collect::<Result<UInt64Array, _>>()?,
137        ),
138    })
139}
140
141/// Parses a decimal number written in plain or scientific notation and returns its value
142/// with `scale` fractional digits, rounded half away from zero.
143///
144/// Every digit of the text is used, so the result is exact apart from that rounding.
145pub fn parse_decimal128(text: &str, precision: u8, scale: i8) -> Result<i128, ArrowError> {
146    let error = |kind| {
147        ArrowError::ParseError(match kind {
148            ErrorKind::Invalid => {
149                format!("can't parse the value {text} as DECIMAL({precision}, {scale})")
150            }
151            ErrorKind::Overflow => {
152                format!("the value {text} is out of range for DECIMAL({precision}, {scale})")
153            }
154        })
155    };
156
157    let (negative, value) = parse_digits(text, precision, scale, true).map_err(error)?;
158    Ok(if negative { -value } else { value })
159}
160
161/// Parses an unsigned integer written in plain or scientific notation.
162///
163/// Every digit of the text is used. Fractional digits are dropped, which is what Arrow's json
164/// reader does with them.
165pub fn parse_uint64(text: &str) -> Result<u64, ArrowError> {
166    let error = |kind| {
167        ArrowError::ParseError(match kind {
168            ErrorKind::Invalid => format!("can't parse the value {text} as UInt64"),
169            ErrorKind::Overflow => format!("the value {text} is out of range for UInt64"),
170        })
171    };
172
173    // A `u64` has at most 20 digits.
174    let (negative, value) = parse_digits(text, 20, 0, false).map_err(error)?;
175    if negative && value != 0 {
176        return Err(error(ErrorKind::Overflow));
177    }
178    u64::try_from(value).map_err(|_| error(ErrorKind::Overflow))
179}
180
181enum ErrorKind {
182    Invalid,
183    Overflow,
184}
185
186/// Returns the sign of the number in `text` and the first `precision` digits at most of
187/// `|number| * 10^scale`. The digits after those are rounded half away from zero with `round`
188/// and dropped without it.
189fn parse_digits(
190    text: &str,
191    precision: u8,
192    scale: i8,
193    round: bool,
194) -> Result<(bool, i128), ErrorKind> {
195    let (negative, number) = match text.as_bytes().first() {
196        Some(b'-') => (true, &text[1..]),
197        Some(b'+') => (false, &text[1..]),
198        _ => (false, text),
199    };
200    let (mantissa, exponent) = match number.find(['e', 'E']) {
201        Some(idx) => {
202            let exponent = &number[idx + 1..];
203            let exponent_digits = exponent.strip_prefix(['+', '-']).unwrap_or(exponent);
204            if exponent_digits.is_empty() || !exponent_digits.bytes().all(|b| b.is_ascii_digit()) {
205                return Err(ErrorKind::Invalid);
206            }
207            // An exponent that doesn't fit is far outside the range of any number here.
208            let exponent = exponent
209                .parse::<i64>()
210                .unwrap_or(if exponent.starts_with('-') {
211                    i64::MIN / 2
212                } else {
213                    i64::MAX / 2
214                });
215            (&number[..idx], exponent.clamp(i64::MIN / 2, i64::MAX / 2))
216        }
217        None => (number, 0),
218    };
219    let (integer, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
220    if (integer.is_empty() && fraction.is_empty())
221        || !integer
222            .bytes()
223            .chain(fraction.bytes())
224            .all(|b| b.is_ascii_digit())
225    {
226        return Err(ErrorKind::Invalid);
227    }
228
229    // The value is `0.d1 d2 d3 ... * 10^point`, where the digits start at the first non-zero
230    // one. The first `kept` digits make the integer part of `value * 10^scale`.
231    let leading_zeros = integer
232        .bytes()
233        .chain(fraction.bytes())
234        .take_while(|b| *b == b'0')
235        .count();
236    let mut digits = integer.bytes().chain(fraction.bytes()).skip(leading_zeros);
237    let point = integer.len() as i64 - leading_zeros as i64 + exponent;
238    let kept = point + scale as i64;
239
240    let mut value = 0_i128;
241    let mut taken = 0_i64;
242    while taken < kept {
243        let digit = match digits.next() {
244            Some(digit) => digit - b'0',
245            // The digits ran out before the decimal point.
246            None if value == 0 => break,
247            None => 0,
248        };
249        if taken >= precision as i64 {
250            return Err(ErrorKind::Overflow);
251        }
252        value = value * 10 + digit as i128;
253        taken += 1;
254    }
255    if round && taken == kept && digits.next().is_some_and(|digit| digit >= b'5') {
256        value += 1;
257        if value >= 10_i128.pow(precision as u32) {
258            return Err(ErrorKind::Overflow);
259        }
260    }
261
262    Ok((negative, value))
263}
264
265#[cfg(test)]
266mod tests {
267    use arrow::array::StringArray;
268    use arrow::datatypes::{Decimal128Type, UInt64Type};
269    use datafusion::physical_plan::common::collect;
270    use futures::stream;
271
272    use super::*;
273
274    #[test]
275    fn test_parse_decimal128() {
276        let cases: &[(&str, u8, i8, i128)] = &[
277            // Plain notation keeps every digit.
278            ("123456789012345678.12", 20, 2, 12345678901234567812),
279            (
280                "-9999999999999999999999999999.9999999999",
281                38,
282                10,
283                -99999999999999999999999999999999999999,
284            ),
285            ("7", 20, 2, 700),
286            ("0", 5, 2, 0),
287            ("+1.5", 5, 2, 150),
288            (".5", 5, 2, 50),
289            ("5.", 5, 2, 500),
290            ("000123.4500", 5, 2, 12345),
291            // More fractional digits than the scale are rounded half away from zero.
292            ("1.005", 20, 2, 101),
293            ("-1.005", 20, 2, -101),
294            ("1.004", 20, 2, 100),
295            ("2.999", 20, 2, 300),
296            ("0.005", 5, 2, 1),
297            ("0.0049", 5, 2, 0),
298            ("-0.0049", 5, 2, 0),
299            ("999.994", 5, 2, 99999),
300            ("0.5", 3, 0, 1),
301            ("-2.5", 3, 0, -3),
302            // Scientific notation.
303            ("1.2500000000000000000000000000000000000000e0", 38, 2, 125),
304            ("0e0", 38, 2, 0),
305            ("0.0e0", 5, 2, 0),
306            ("1e2", 20, 2, 10000),
307            ("1.5e-1", 20, 2, 15),
308            ("1.25E+1", 20, 2, 1250),
309            ("12345e-3", 20, 2, 1235),
310            ("0.00012345e5", 5, 2, 1235),
311            ("5e-3", 20, 2, 1),
312            ("4.9e-3", 20, 2, 0),
313            ("1e37", 38, 0, 10_i128.pow(37)),
314            ("1e-999999999999999999999", 20, 2, 0),
315            ("0e999999999999999999999", 20, 2, 0),
316            // A negative scale.
317            ("150", 3, -1, 15),
318            ("144", 3, -1, 14),
319        ];
320        for (text, precision, scale, expected) in cases {
321            assert_eq!(
322                parse_decimal128(text, *precision, *scale).unwrap(),
323                *expected,
324                "{text} as DECIMAL({precision}, {scale})"
325            );
326        }
327
328        for text in [
329            // Out of range, also after rounding.
330            "1000",
331            "1e3",
332            "999.995",
333            "1e999999999999999999999",
334            // Not a number.
335            "",
336            "-",
337            ".",
338            "e5",
339            "1e",
340            "1e+",
341            "1e1.5",
342            "1.2.3",
343            "1,5",
344            " 1",
345            "--1",
346            "NaN",
347            "inf",
348        ] {
349            assert!(
350                parse_decimal128(text, 5, 2).is_err(),
351                "{text} as DECIMAL(5, 2)"
352            );
353        }
354    }
355
356    #[test]
357    fn test_parse_uint64() {
358        let cases: &[(&str, u64)] = &[
359            ("0", 0),
360            ("7", 7),
361            ("+7", 7),
362            ("18446744073709551615", u64::MAX),
363            // A `Float64` can't hold these.
364            ("9007199254740993e0", 9007199254740993),
365            ("9007199254740993.0", 9007199254740993),
366            ("1.8446744073709551615e19", u64::MAX),
367            ("184467440737095516150e-1", u64::MAX),
368            ("1e3", 1000),
369            ("0e0", 0),
370            // Fractional digits are dropped.
371            ("1.5", 1),
372            ("1.999", 1),
373            ("15e-1", 1),
374            ("0.9", 0),
375            ("-0", 0),
376            ("-0.9", 0),
377            ("1e-999999999999999999999", 0),
378        ];
379        for (text, expected) in cases {
380            assert_eq!(parse_uint64(text).unwrap(), *expected, "{text}");
381        }
382
383        for text in [
384            "18446744073709551616",
385            "1.8446744073709551616e19",
386            "1e20",
387            "1e999999999999999999999",
388            "-1",
389            "-1.5",
390            "",
391            "-",
392            "1e",
393            "1,5",
394            " 1",
395            "NaN",
396        ] {
397            assert!(parse_uint64(text).is_err(), "{text}");
398        }
399    }
400
401    #[tokio::test]
402    async fn test_parse_number_columns() {
403        let schema = Arc::new(Schema::new(vec![
404            Field::new("k", DataType::Utf8, true),
405            Field::new("price", DataType::Utf8, true),
406            Field::new("id", DataType::Utf8, true),
407        ]));
408        let batch = RecordBatch::try_new(
409            schema.clone(),
410            vec![
411                Arc::new(StringArray::from(vec!["a", "b", "c", "d"])),
412                Arc::new(StringArray::from(vec![
413                    Some("1.2500000000000000000000000000000000000000e0"),
414                    Some(""),
415                    None,
416                    Some("-0.005"),
417                ])),
418                Arc::new(StringArray::from(vec![
419                    Some("9007199254740993e0"),
420                    Some(""),
421                    None,
422                    Some("18446744073709551615"),
423                ])),
424            ],
425        )
426        .unwrap();
427        let stream = Box::pin(RecordBatchStreamAdapter::new(
428            schema.clone(),
429            stream::iter(vec![Ok(batch.clone())]),
430        ));
431
432        let price = TextNumber::Decimal128 {
433            precision: 38,
434            scale: 2,
435        };
436        let numbers = vec![None, Some(price), Some(TextNumber::UInt64)];
437        let stream = parse_number_columns(stream, numbers.clone(), true);
438        let stream_schema = stream.schema();
439        assert_eq!(
440            stream_schema.field(1),
441            &Field::new("price", DataType::Decimal128(38, 2), true)
442        );
443        let batches = collect(stream).await.unwrap();
444        assert_eq!(batches.len(), 1);
445        assert_eq!(batches[0].column(0), batch.column(0));
446        let prices = batches[0].column(1).as_primitive::<Decimal128Type>();
447        assert_eq!(
448            prices.iter().collect::<Vec<_>>(),
449            vec![Some(125), None, None, Some(-1)]
450        );
451        assert_eq!(
452            stream_schema.field(2),
453            &Field::new("id", DataType::UInt64, true)
454        );
455        let ids = batches[0].column(2).as_primitive::<UInt64Type>();
456        assert_eq!(
457            ids.iter().collect::<Vec<_>>(),
458            vec![Some(9007199254740993), None, None, Some(u64::MAX)]
459        );
460
461        // An empty string is only NULL when the caller asks for it.
462        let stream = Box::pin(RecordBatchStreamAdapter::new(
463            schema.clone(),
464            stream::iter(vec![Ok(batch.clone())]),
465        ));
466        let error = collect(parse_number_columns(stream, numbers, false))
467            .await
468            .unwrap_err();
469        assert!(
470            error
471                .to_string()
472                .contains("can't parse the value  as DECIMAL(38, 2)"),
473            "{error}"
474        );
475
476        let stream = Box::pin(RecordBatchStreamAdapter::new(
477            schema,
478            stream::iter(vec![Ok(batch)]),
479        ));
480        let stream = parse_number_columns(stream, vec![Some(price), None, None], true);
481        let error = collect(stream).await.unwrap_err();
482        assert!(
483            error
484                .to_string()
485                .contains("can't parse the value a as DECIMAL(38, 2)"),
486            "{error}"
487        );
488    }
489}