fix: keep exact DECIMAL and BIGINT UNSIGNED values in COPY FROM csv and json (#10560)

* fix: keep exact DECIMAL and UInt64 values in COPY FROM csv and json

Signed-off-by: Samarth Jaiswal <samarthjaiswal30@gmail.com>

* style: format the reader schema test

Signed-off-by: Samarth Jaiswal <samarthjaiswal30@gmail.com>

* test: add the expected output of the exact numbers case

Signed-off-by: Samarth Jaiswal <samarthjaiswal30@gmail.com>

* fix: round decimals with extra fractional digits in COPY FROM

Signed-off-by: Samarth Jaiswal <samarthjaiswal30@gmail.com>

* fix: parse decimals from text in COPY FROM csv and json

Arrow's decimal decoding is wrong for some numbers in scientific
notation and drops the digits beyond the scale. Read a decimal column
as a string and parse it, so that every digit is used and the value is
rounded as the cast from a float did.

Signed-off-by: Samarth Jaiswal <samarthjaiswal30@gmail.com>

* fix: read unsigned integers from text and reject empty strings in COPY FROM json

Arrow's json reader parses an integer in scientific notation through a
Float64, so 9007199254740993e0 lost its last digit in a BIGINT UNSIGNED
column. Such a column is now read as text and parsed from every digit,
like a DECIMAL column.

An empty json string loaded into a DECIMAL column as NULL. It is an
error again, and only an empty csv field is read as NULL.

Signed-off-by: Samarth Jaiswal <samarthjaiswal30@gmail.com>

---------

Signed-off-by: Samarth Jaiswal <samarthjaiswal30@gmail.com>
This commit is contained in:
Samarth Jaiswal
2026-11-24 18:18:35 +00:00
committed by GitHub
parent 93ddb89ffc
commit f4ff272f37
11 changed files with 1343 additions and 18 deletions
+1
View File
@@ -13,6 +13,7 @@
// limitations under the License.
pub mod csv;
pub mod decimal;
pub mod json;
pub mod orc;
pub mod parquet;
@@ -0,0 +1,489 @@
// Copyright 2023 Greptime Team
//
// Licensed 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.
//! Reads decimal and unsigned integer columns from the text of a csv or json file.
//!
//! A file reader that decodes a number into a `Float64` loses the digits a `Float64` can't
//! hold. Arrow's own decimal decoding is wrong for some numbers in scientific notation, and its
//! json integer decoding goes through a `Float64` for them. So the readers hand over the text
//! of such a column and [`parse_number_columns`] parses it.
use std::sync::Arc;
use arrow::array::{Array, ArrayRef, AsArray, Decimal128Array, UInt64Array};
use arrow::error::ArrowError;
use arrow::record_batch::RecordBatch;
use arrow_schema::{DataType, Field, Schema, SchemaRef};
use datafusion::error::DataFusionError;
use datafusion::physical_plan::SendableRecordBatchStream;
use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
use futures::StreamExt;
/// The type to parse the text of a column into.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextNumber {
Decimal128 { precision: u8, scale: i8 },
UInt64,
}
impl TextNumber {
fn data_type(&self) -> DataType {
match self {
TextNumber::Decimal128 { precision, scale } => DataType::Decimal128(*precision, *scale),
TextNumber::UInt64 => DataType::UInt64,
}
}
}
/// Parses the string columns of `stream` that have a type in `numbers` into columns of that
/// type. `numbers` has one entry for each column of the stream.
///
/// With `empty_as_null` an empty string is read as NULL, which is what an empty csv field is
/// for a number. Without it an empty string is an error, like any other text that is not a
/// number.
pub fn parse_number_columns(
stream: SendableRecordBatchStream,
numbers: Vec<Option<TextNumber>>,
empty_as_null: bool,
) -> SendableRecordBatchStream {
if numbers.iter().all(Option::is_none) {
return stream;
}
let input_schema = stream.schema();
let fields = input_schema
.fields()
.iter()
.zip(&numbers)
.map(|(field, number)| match number {
Some(number) => Arc::new(Field::clone(field).with_data_type(number.data_type())),
None => field.clone(),
})
.collect::<Vec<_>>();
let schema = Arc::new(Schema::new_with_metadata(
fields,
input_schema.metadata().clone(),
));
let output_schema = schema.clone();
let stream = stream.map(move |batch| {
parse_number_batch(&batch?, &output_schema, &numbers, empty_as_null)
.map_err(DataFusionError::from)
});
Box::pin(RecordBatchStreamAdapter::new(schema, stream))
}
fn parse_number_batch(
batch: &RecordBatch,
schema: &SchemaRef,
numbers: &[Option<TextNumber>],
empty_as_null: bool,
) -> Result<RecordBatch, ArrowError> {
let columns = batch
.columns()
.iter()
.zip(numbers)
.map(|(column, number)| match number {
Some(number) => parse_number_array(column, *number, empty_as_null),
None => Ok(column.clone()),
})
.collect::<Result<Vec<_>, _>>()?;
RecordBatch::try_new(schema.clone(), columns)
}
fn parse_number_array(
array: &ArrayRef,
number: TextNumber,
empty_as_null: bool,
) -> Result<ArrayRef, ArrowError> {
let strings = array.as_string_opt::<i32>().ok_or_else(|| {
ArrowError::CastError(format!(
"expected a string column to parse {} from, got {}",
number.data_type(),
array.data_type()
))
})?;
let texts = strings
.iter()
.map(|text| text.filter(|text| !(empty_as_null && text.is_empty())));
Ok(match number {
TextNumber::Decimal128 { precision, scale } => Arc::new(
texts
.map(|text| {
text.map(|text| parse_decimal128(text, precision, scale))
.transpose()
})
.collect::<Result<Decimal128Array, _>>()?
.with_precision_and_scale(precision, scale)?,
),
TextNumber::UInt64 => Arc::new(
texts
.map(|text| text.map(parse_uint64).transpose())
.collect::<Result<UInt64Array, _>>()?,
),
})
}
/// Parses a decimal number written in plain or scientific notation and returns its value
/// with `scale` fractional digits, rounded half away from zero.
///
/// Every digit of the text is used, so the result is exact apart from that rounding.
pub fn parse_decimal128(text: &str, precision: u8, scale: i8) -> Result<i128, ArrowError> {
let error = |kind| {
ArrowError::ParseError(match kind {
ErrorKind::Invalid => {
format!("can't parse the value {text} as DECIMAL({precision}, {scale})")
}
ErrorKind::Overflow => {
format!("the value {text} is out of range for DECIMAL({precision}, {scale})")
}
})
};
let (negative, value) = parse_digits(text, precision, scale, true).map_err(error)?;
Ok(if negative { -value } else { value })
}
/// Parses an unsigned integer written in plain or scientific notation.
///
/// Every digit of the text is used. Fractional digits are dropped, which is what Arrow's json
/// reader does with them.
pub fn parse_uint64(text: &str) -> Result<u64, ArrowError> {
let error = |kind| {
ArrowError::ParseError(match kind {
ErrorKind::Invalid => format!("can't parse the value {text} as UInt64"),
ErrorKind::Overflow => format!("the value {text} is out of range for UInt64"),
})
};
// A `u64` has at most 20 digits.
let (negative, value) = parse_digits(text, 20, 0, false).map_err(error)?;
if negative && value != 0 {
return Err(error(ErrorKind::Overflow));
}
u64::try_from(value).map_err(|_| error(ErrorKind::Overflow))
}
enum ErrorKind {
Invalid,
Overflow,
}
/// Returns the sign of the number in `text` and the first `precision` digits at most of
/// `|number| * 10^scale`. The digits after those are rounded half away from zero with `round`
/// and dropped without it.
fn parse_digits(
text: &str,
precision: u8,
scale: i8,
round: bool,
) -> Result<(bool, i128), ErrorKind> {
let (negative, number) = match text.as_bytes().first() {
Some(b'-') => (true, &text[1..]),
Some(b'+') => (false, &text[1..]),
_ => (false, text),
};
let (mantissa, exponent) = match number.find(['e', 'E']) {
Some(idx) => {
let exponent = &number[idx + 1..];
let exponent_digits = exponent.strip_prefix(['+', '-']).unwrap_or(exponent);
if exponent_digits.is_empty() || !exponent_digits.bytes().all(|b| b.is_ascii_digit()) {
return Err(ErrorKind::Invalid);
}
// An exponent that doesn't fit is far outside the range of any number here.
let exponent = exponent
.parse::<i64>()
.unwrap_or(if exponent.starts_with('-') {
i64::MIN / 2
} else {
i64::MAX / 2
});
(&number[..idx], exponent.clamp(i64::MIN / 2, i64::MAX / 2))
}
None => (number, 0),
};
let (integer, fraction) = mantissa.split_once('.').unwrap_or((mantissa, ""));
if (integer.is_empty() && fraction.is_empty())
|| !integer
.bytes()
.chain(fraction.bytes())
.all(|b| b.is_ascii_digit())
{
return Err(ErrorKind::Invalid);
}
// The value is `0.d1 d2 d3 ... * 10^point`, where the digits start at the first non-zero
// one. The first `kept` digits make the integer part of `value * 10^scale`.
let leading_zeros = integer
.bytes()
.chain(fraction.bytes())
.take_while(|b| *b == b'0')
.count();
let mut digits = integer.bytes().chain(fraction.bytes()).skip(leading_zeros);
let point = integer.len() as i64 - leading_zeros as i64 + exponent;
let kept = point + scale as i64;
let mut value = 0_i128;
let mut taken = 0_i64;
while taken < kept {
let digit = match digits.next() {
Some(digit) => digit - b'0',
// The digits ran out before the decimal point.
None if value == 0 => break,
None => 0,
};
if taken >= precision as i64 {
return Err(ErrorKind::Overflow);
}
value = value * 10 + digit as i128;
taken += 1;
}
if round && taken == kept && digits.next().is_some_and(|digit| digit >= b'5') {
value += 1;
if value >= 10_i128.pow(precision as u32) {
return Err(ErrorKind::Overflow);
}
}
Ok((negative, value))
}
#[cfg(test)]
mod tests {
use arrow::array::StringArray;
use arrow::datatypes::{Decimal128Type, UInt64Type};
use datafusion::physical_plan::common::collect;
use futures::stream;
use super::*;
#[test]
fn test_parse_decimal128() {
let cases: &[(&str, u8, i8, i128)] = &[
// Plain notation keeps every digit.
("123456789012345678.12", 20, 2, 12345678901234567812),
(
"-9999999999999999999999999999.9999999999",
38,
10,
-99999999999999999999999999999999999999,
),
("7", 20, 2, 700),
("0", 5, 2, 0),
("+1.5", 5, 2, 150),
(".5", 5, 2, 50),
("5.", 5, 2, 500),
("000123.4500", 5, 2, 12345),
// More fractional digits than the scale are rounded half away from zero.
("1.005", 20, 2, 101),
("-1.005", 20, 2, -101),
("1.004", 20, 2, 100),
("2.999", 20, 2, 300),
("0.005", 5, 2, 1),
("0.0049", 5, 2, 0),
("-0.0049", 5, 2, 0),
("999.994", 5, 2, 99999),
("0.5", 3, 0, 1),
("-2.5", 3, 0, -3),
// Scientific notation.
("1.2500000000000000000000000000000000000000e0", 38, 2, 125),
("0e0", 38, 2, 0),
("0.0e0", 5, 2, 0),
("1e2", 20, 2, 10000),
("1.5e-1", 20, 2, 15),
("1.25E+1", 20, 2, 1250),
("12345e-3", 20, 2, 1235),
("0.00012345e5", 5, 2, 1235),
("5e-3", 20, 2, 1),
("4.9e-3", 20, 2, 0),
("1e37", 38, 0, 10_i128.pow(37)),
("1e-999999999999999999999", 20, 2, 0),
("0e999999999999999999999", 20, 2, 0),
// A negative scale.
("150", 3, -1, 15),
("144", 3, -1, 14),
];
for (text, precision, scale, expected) in cases {
assert_eq!(
parse_decimal128(text, *precision, *scale).unwrap(),
*expected,
"{text} as DECIMAL({precision}, {scale})"
);
}
for text in [
// Out of range, also after rounding.
"1000",
"1e3",
"999.995",
"1e999999999999999999999",
// Not a number.
"",
"-",
".",
"e5",
"1e",
"1e+",
"1e1.5",
"1.2.3",
"1,5",
" 1",
"--1",
"NaN",
"inf",
] {
assert!(
parse_decimal128(text, 5, 2).is_err(),
"{text} as DECIMAL(5, 2)"
);
}
}
#[test]
fn test_parse_uint64() {
let cases: &[(&str, u64)] = &[
("0", 0),
("7", 7),
("+7", 7),
("18446744073709551615", u64::MAX),
// A `Float64` can't hold these.
("9007199254740993e0", 9007199254740993),
("9007199254740993.0", 9007199254740993),
("1.8446744073709551615e19", u64::MAX),
("184467440737095516150e-1", u64::MAX),
("1e3", 1000),
("0e0", 0),
// Fractional digits are dropped.
("1.5", 1),
("1.999", 1),
("15e-1", 1),
("0.9", 0),
("-0", 0),
("-0.9", 0),
("1e-999999999999999999999", 0),
];
for (text, expected) in cases {
assert_eq!(parse_uint64(text).unwrap(), *expected, "{text}");
}
for text in [
"18446744073709551616",
"1.8446744073709551616e19",
"1e20",
"1e999999999999999999999",
"-1",
"-1.5",
"",
"-",
"1e",
"1,5",
" 1",
"NaN",
] {
assert!(parse_uint64(text).is_err(), "{text}");
}
}
#[tokio::test]
async fn test_parse_number_columns() {
let schema = Arc::new(Schema::new(vec![
Field::new("k", DataType::Utf8, true),
Field::new("price", DataType::Utf8, true),
Field::new("id", DataType::Utf8, true),
]));
let batch = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(StringArray::from(vec!["a", "b", "c", "d"])),
Arc::new(StringArray::from(vec![
Some("1.2500000000000000000000000000000000000000e0"),
Some(""),
None,
Some("-0.005"),
])),
Arc::new(StringArray::from(vec![
Some("9007199254740993e0"),
Some(""),
None,
Some("18446744073709551615"),
])),
],
)
.unwrap();
let stream = Box::pin(RecordBatchStreamAdapter::new(
schema.clone(),
stream::iter(vec![Ok(batch.clone())]),
));
let price = TextNumber::Decimal128 {
precision: 38,
scale: 2,
};
let numbers = vec![None, Some(price), Some(TextNumber::UInt64)];
let stream = parse_number_columns(stream, numbers.clone(), true);
let stream_schema = stream.schema();
assert_eq!(
stream_schema.field(1),
&Field::new("price", DataType::Decimal128(38, 2), true)
);
let batches = collect(stream).await.unwrap();
assert_eq!(batches.len(), 1);
assert_eq!(batches[0].column(0), batch.column(0));
let prices = batches[0].column(1).as_primitive::<Decimal128Type>();
assert_eq!(
prices.iter().collect::<Vec<_>>(),
vec![Some(125), None, None, Some(-1)]
);
assert_eq!(
stream_schema.field(2),
&Field::new("id", DataType::UInt64, true)
);
let ids = batches[0].column(2).as_primitive::<UInt64Type>();
assert_eq!(
ids.iter().collect::<Vec<_>>(),
vec![Some(9007199254740993), None, None, Some(u64::MAX)]
);
// An empty string is only NULL when the caller asks for it.
let stream = Box::pin(RecordBatchStreamAdapter::new(
schema.clone(),
stream::iter(vec![Ok(batch.clone())]),
));
let error = collect(parse_number_columns(stream, numbers, false))
.await
.unwrap_err();
assert!(
error
.to_string()
.contains("can't parse the value as DECIMAL(38, 2)"),
"{error}"
);
let stream = Box::pin(RecordBatchStreamAdapter::new(
schema,
stream::iter(vec![Ok(batch)]),
));
let stream = parse_number_columns(stream, vec![Some(price), None, None], true);
let error = collect(stream).await.unwrap_err();
assert!(
error
.to_string()
.contains("can't parse the value a as DECIMAL(38, 2)"),
"{error}"
);
}
}
+156 -2
View File
@@ -13,18 +13,24 @@
// limitations under the License.
use std::collections::HashMap;
use std::io::BufReader;
use std::io::{self, BufReader};
use std::str::FromStr;
use std::task::Poll;
use arrow::error::ArrowError;
use arrow::json;
use arrow::json::WriterBuilder;
use arrow::json::reader::{ValueIter, infer_json_schema_from_iterator};
use arrow::json::writer::LineDelimited;
use arrow::record_batch::RecordBatch;
use arrow_schema::Schema;
use arrow_schema::{Schema, SchemaRef};
use async_trait::async_trait;
use bytes::{Buf, Bytes};
use common_runtime;
use datafusion::physical_plan::SendableRecordBatchStream;
use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
use futures::StreamExt;
use futures::stream::BoxStream;
use object_store::ObjectStore;
use snafu::ResultExt;
use tokio_util::compat::FuturesAsyncReadCompatExt;
@@ -120,6 +126,87 @@ impl FileFormat for JsonFormat {
}
}
/// Returns a stream of the json file at `path` that reads the fields of `schema`.
///
/// Unlike the stream of a `JsonSource`, a string column also takes a number or a boolean, as
/// the text it has in the file. So a column whose numbers must be parsed from every digit can
/// be read as a string, see [`parse_number_columns`](super::decimal::parse_number_columns).
pub async fn json_text_stream(
store: &ObjectStore,
path: &str,
schema: SchemaRef,
format: &JsonFormat,
batch_size: usize,
) -> Result<SendableRecordBatchStream> {
let meta = store
.stat(path)
.await
.context(error::ReadObjectSnafu { path })?;
let reader = store
.reader(path)
.await
.context(error::ReadObjectSnafu { path })?
.into_bytes_stream(0..meta.content_length())
.await
.context(error::ReadObjectSnafu { path })?;
let reader = format.compression_type.convert_stream(reader).boxed();
json_text_stream_from_reader(reader, schema, batch_size)
}
fn json_text_stream_from_reader(
reader: BoxStream<'static, io::Result<Bytes>>,
schema: SchemaRef,
batch_size: usize,
) -> Result<SendableRecordBatchStream> {
let mut builder = Some(
json::ReaderBuilder::new(schema.clone())
.with_coerce_primitive(true)
.with_batch_size(batch_size),
);
let mut decoder = None;
let mut upstream = reader.fuse();
let mut buffered = Bytes::new();
let mut input_finished = false;
let stream = futures::stream::poll_fn(move |cx| {
if let Some(builder) = builder.take() {
decoder = Some(builder.build_decoder()?);
}
let Some(decoder) = decoder.as_mut() else {
return Poll::Ready(None);
};
loop {
if input_finished {
return Poll::Ready(decoder.flush().transpose());
}
if buffered.is_empty() {
match futures::ready!(upstream.poll_next_unpin(cx)) {
Some(Ok(bytes)) => buffered = bytes,
Some(Err(error)) => return Poll::Ready(Some(Err(error.into()))),
None => input_finished = true,
}
continue;
}
let decoded = decoder.decode(buffered.as_ref())?;
buffered.advance(decoded);
// The decoder stops before the end of the input once it holds a full batch.
if !buffered.is_empty()
&& let Some(batch) = decoder.flush()?
{
return Poll::Ready(Some(Ok(batch)));
}
}
})
.map(|result: std::result::Result<RecordBatch, ArrowError>| result.map_err(Into::into));
Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream)))
}
pub async fn stream_to_json(
stream: SendableRecordBatchStream,
store: ObjectStore,
@@ -162,6 +249,7 @@ impl DfRecordBatchEncoder for json::Writer<SharedBuffer, LineDelimited> {
mod tests {
use std::sync::Arc;
use arrow::array::AsArray;
use common_recordbatch::adapter::DfRecordBatchStreamAdapter;
use common_recordbatch::{RecordBatch, RecordBatches};
use common_test_util::find_workspace_path;
@@ -183,6 +271,72 @@ mod tests {
.to_string()
}
#[tokio::test]
async fn test_json_text_stream() {
let schema = Arc::new(arrow_schema::Schema::new(vec![
arrow_schema::Field::new("price", arrow_schema::DataType::Utf8, true),
arrow_schema::Field::new("k", arrow_schema::DataType::Utf8, true),
arrow_schema::Field::new("n", arrow_schema::DataType::Int64, true),
]));
let input: &[u8] = br#"{"k":"a","price":1.2500000000000000000000000000000000000000e0,"n":1}
{"k":"b","price":0e0,"n":2,"unknown":true}
{"k":"c","price":null}
{"n":4,"price":123456789012345678.12,"k":"d"}
{"k":"e","price":"5"}"#;
// Every size of input chunk and of batch gives the same rows.
for chunk_size in [1, 7, input.len()] {
for batch_size in [1, 2, 8192] {
let chunks = input
.chunks(chunk_size)
.map(|chunk| Ok(Bytes::copy_from_slice(chunk)))
.collect::<Vec<_>>();
let stream = json_text_stream_from_reader(
futures::stream::iter(chunks).boxed(),
schema.clone(),
batch_size,
)
.unwrap();
let batches = stream.try_collect::<Vec<_>>().await.unwrap();
assert!(batches.iter().all(|batch| batch.num_rows() <= batch_size));
let batch = arrow::compute::concat_batches(&schema, &batches).unwrap();
let prices = batch.column(0).as_string::<i32>();
assert_eq!(
prices.iter().collect::<Vec<_>>(),
vec![
Some("1.2500000000000000000000000000000000000000e0"),
Some("0e0"),
None,
Some("123456789012345678.12"),
Some("5"),
]
);
let keys = batch.column(1).as_string::<i32>();
assert_eq!(
keys.iter().collect::<Vec<_>>(),
vec![Some("a"), Some("b"), Some("c"), Some("d"), Some("e")]
);
let numbers = batch
.column(2)
.as_primitive::<arrow::datatypes::Int64Type>();
assert_eq!(
numbers.iter().collect::<Vec<_>>(),
vec![Some(1), Some(2), None, Some(4), None]
);
}
}
// A record that is cut off is an error.
let stream = json_text_stream_from_reader(
futures::stream::iter(vec![Ok(Bytes::from_static(br#"{"k":"a","price":1"#))]).boxed(),
schema,
8192,
)
.unwrap();
assert!(stream.try_collect::<Vec<_>>().await.is_err());
}
#[tokio::test]
async fn infer_schema_basic() {
let json = JsonFormat::default();
+196 -16
View File
@@ -23,7 +23,8 @@ use common_base::readable_size::ReadableSize;
use common_datasource::file_format::csv::{
CsvFormat, is_skippable_arrow_error, tolerant_csv_stream,
};
use common_datasource::file_format::json::JsonFormat;
use common_datasource::file_format::decimal::{TextNumber, parse_number_columns};
use common_datasource::file_format::json::{JsonFormat, json_text_stream};
use common_datasource::file_format::orc::{ReaderAdapter, infer_orc_schema, new_orc_stream_reader};
use common_datasource::file_format::{FileFormat, Format, file_to_stream};
use common_datasource::lister::{Lister, Source};
@@ -40,7 +41,7 @@ use datafusion_common::arrow::error::ArrowError;
use datafusion_common::config::CsvOptions;
use datafusion_expr::Expr;
use datatypes::arrow::compute::can_cast_types;
use datatypes::arrow::datatypes::{DataType as ArrowDataType, Schema, SchemaRef};
use datatypes::arrow::datatypes::{DataType as ArrowDataType, FieldRef, Schema, SchemaRef};
use datatypes::arrow::record_batch::RecordBatch;
use datatypes::vectors::Helper;
use futures_util::StreamExt;
@@ -241,7 +242,9 @@ impl StatementExecutor {
let options = CsvOptions::default()
.with_has_header(format.has_header)
.with_delimiter(format.delimiter);
let csv_source = CsvSource::new(schema.clone())
let reader_schema = exact_numeric_reader_schema(schema, &compat_schema, false);
let numbers = text_number_columns(schema, &compat_schema, &projection, false);
let csv_source = CsvSource::new(Arc::new(reader_schema))
.with_csv_options(options)
.with_batch_size(DEFAULT_BATCH_SIZE);
let stream = if format.skip_bad_records {
@@ -257,7 +260,7 @@ impl StatementExecutor {
.await
.context(error::BuildFileStreamSnafu)?
} else {
file_to_stream(
let stream = file_to_stream(
object_store,
path,
csv_source,
@@ -265,7 +268,9 @@ impl StatementExecutor {
format.compression_type,
)
.await
.context(error::BuildFileStreamSnafu)?
.context(error::BuildFileStreamSnafu)?;
// An empty csv field is NULL.
parse_number_columns(stream, numbers, true)
};
let stream = Box::pin(
@@ -292,17 +297,39 @@ impl StatementExecutor {
.context(error::ProjectSchemaSnafu)?,
);
let json_source =
JsonSource::new(schema.clone()).with_batch_size(DEFAULT_BATCH_SIZE);
let stream = file_to_stream(
object_store,
path,
json_source,
Some(projection),
format.compression_type,
)
.await
.context(error::BuildFileStreamSnafu)?;
let reader_schema = exact_numeric_reader_schema(schema, &compat_schema, true);
let numbers = text_number_columns(schema, &compat_schema, &projection, true);
let stream = if numbers.iter().any(Option::is_some) {
// Only this stream reads a number as its text.
let projected_schema = Arc::new(
reader_schema
.project(&projection)
.context(error::ProjectSchemaSnafu)?,
);
json_text_stream(
object_store,
path,
projected_schema,
format,
DEFAULT_BATCH_SIZE,
)
.await
.context(error::BuildFileStreamSnafu)?
} else {
let json_source = JsonSource::new(Arc::new(reader_schema))
.with_batch_size(DEFAULT_BATCH_SIZE);
file_to_stream(
object_store,
path,
json_source,
Some(projection),
format.compression_type,
)
.await
.context(error::BuildFileStreamSnafu)?
};
// An empty json string is not a number, so it is an error like other text.
let stream = parse_number_columns(stream, numbers, false);
Ok(Box::pin(
// The projection is already applied in the JSON reader when we created the stream,
@@ -722,6 +749,78 @@ fn can_cast_types_for_greptime(from: &ArrowDataType, to: &ArrowDataType) -> bool
can_cast_types(from, to)
}
/// Returns the schema to read the file with.
///
/// Schema inference reads a number as `Int64` or `Float64`. Casting such a column to a wider
/// table type afterwards rounds every value a `Float64` can't hold, and a value outside the
/// `Int64` range fails to parse. So these columns are read as a string and parsed by
/// [`parse_number_columns`], see [`text_number_columns`]:
/// - A `Decimal128` column.
/// - A `UInt64` column when `uint64_text` is set, which is for json. The CSV reader keeps the
/// inferred type for it.
fn exact_numeric_reader_schema(file: &SchemaRef, compat: &SchemaRef, uint64_text: bool) -> Schema {
let fields = file
.fields()
.iter()
.enumerate()
.map(|(idx, file_field)| {
match text_number(file_field, compat.fields().get(idx), uint64_text) {
Some(_) => Arc::new(
file_field
.as_ref()
.clone()
.with_data_type(ArrowDataType::Utf8),
),
None => file_field.clone(),
}
})
.collect::<Vec<_>>();
Schema::new_with_metadata(fields, file.metadata().clone())
}
/// Returns the type to parse each projected column into that
/// [`exact_numeric_reader_schema`] reads as a string, and `None` for the other columns.
fn text_number_columns(
file: &SchemaRef,
compat: &SchemaRef,
projection: &[usize],
uint64_text: bool,
) -> Vec<Option<TextNumber>> {
projection
.iter()
.map(|idx| {
text_number(
file.fields().get(*idx)?,
compat.fields().get(*idx),
uint64_text,
)
})
.collect()
}
fn text_number(
file_field: &FieldRef,
compat_field: Option<&FieldRef>,
uint64_text: bool,
) -> Option<TextNumber> {
if !is_inferred_number(file_field.data_type()) {
return None;
}
match compat_field?.data_type() {
ArrowDataType::Decimal128(precision, scale) => Some(TextNumber::Decimal128 {
precision: *precision,
scale: *scale,
}),
ArrowDataType::UInt64 if uint64_text => Some(TextNumber::UInt64),
_ => None,
}
}
fn is_inferred_number(data_type: &ArrowDataType) -> bool {
matches!(data_type, ArrowDataType::Int64 | ArrowDataType::Float64)
}
fn csv_reader_schema_for_skip_bad_records(file: &SchemaRef, compat: &SchemaRef) -> Schema {
let fields = file
.fields()
@@ -1420,6 +1519,87 @@ mod tests {
);
}
#[test]
fn test_exact_numeric_reader_schema() {
let file_schema = make_test_schema(&[
Field::new("price", DataType::Float64, true),
Field::new("amount", DataType::Int64, true),
Field::new("count", DataType::Float64, true),
Field::new("id", DataType::Int64, true),
Field::new("cpu", DataType::Float64, true),
Field::new("quoted", DataType::Utf8, true),
Field::new("extra", DataType::Float64, true),
]);
let compat_schema = make_test_schema(&[
Field::new("price", DataType::Decimal128(38, 10), false),
Field::new("amount", DataType::Decimal128(20, 2), true),
Field::new("count", DataType::UInt64, true),
Field::new("id", DataType::UInt64, true),
Field::new("cpu", DataType::Float64, true),
Field::new("quoted", DataType::Decimal128(38, 10), true),
]);
// A decimal column is read as a string, to be parsed from every digit.
let csv_schema = exact_numeric_reader_schema(&file_schema, &compat_schema, false);
assert_eq!(
csv_schema.field(0),
&Field::new("price", DataType::Utf8, true)
);
assert_eq!(
csv_schema.field(1),
&Field::new("amount", DataType::Utf8, true)
);
for idx in 2..file_schema.fields().len() {
assert_eq!(csv_schema.field(idx), file_schema.field(idx));
}
let json_schema = exact_numeric_reader_schema(&file_schema, &compat_schema, true);
assert_eq!(
json_schema.field(0),
&Field::new("price", DataType::Utf8, true)
);
assert_eq!(
json_schema.field(1),
&Field::new("amount", DataType::Utf8, true)
);
assert_eq!(
json_schema.field(2),
&Field::new("count", DataType::Utf8, true)
);
assert_eq!(
json_schema.field(3),
&Field::new("id", DataType::Utf8, true)
);
for idx in 4..file_schema.fields().len() {
assert_eq!(json_schema.field(idx), file_schema.field(idx));
}
// The quoted column is not an inferred number, so it is not parsed here.
let amount = TextNumber::Decimal128 {
precision: 20,
scale: 2,
};
let price = TextNumber::Decimal128 {
precision: 38,
scale: 10,
};
assert_eq!(
text_number_columns(&file_schema, &compat_schema, &[5, 1, 4, 0, 6, 3], false),
vec![None, Some(amount), None, Some(price), None, None]
);
assert_eq!(
text_number_columns(&file_schema, &compat_schema, &[5, 1, 4, 0, 6, 3], true),
vec![
None,
Some(amount),
None,
Some(price),
None,
Some(TextNumber::UInt64)
]
);
}
fn make_csv_metadata(schema: Arc<Schema>, has_header: bool) -> FileMetadata {
FileMetadata::Csv {
schema,
@@ -3594,6 +3594,143 @@ async fn test_execute_copy_from_orc_with_cast(instance: Arc<dyn MockInstance>) {
check_output_stream(output, expected).await;
}
// Numbers in scientific notation, and with more fractional digits than the scale, load into a
// DECIMAL column with the value they have in the file.
#[apply(standalone_instance_case)]
async fn test_execute_copy_from_decimal_notation(instance: Arc<dyn MockInstance>) {
common_telemetry::init_default_ut_logging();
let instance = instance.frontend();
for format in ["csv", "json"] {
let table_name = format!("decimal_notation_{format}");
assert!(matches!(
execute_sql(
&instance,
&format!(
"create table {table_name}(k string, price decimal(38, 2), ts timestamp time index, primary key(k));"
),
)
.await
.data,
OutputData::AffectedRows(0)
));
let filepath =
find_testing_resource(&format!("/tests/data/{format}/decimal_notation.{format}"));
let output = execute_sql(
&instance,
&format!("copy {table_name} from '{filepath}' WITH(FORMAT='{format}');"),
)
.await
.data;
assert!(matches!(output, OutputData::AffectedRows(7)));
let output = execute_sql(
&instance,
&format!("select k, price from {table_name} order by k;"),
)
.await
.data;
let expected = r#"+---+-----------------------------------------+
| k | price |
+---+-----------------------------------------+
| a | 1.25 |
| b | 0.00 |
| c | 12.35 |
| d | 1.01 |
| e | -1.01 |
| f | 123456789012345678901234567890123456.78 |
| g | |
+---+-----------------------------------------+"#;
check_output_stream(output, expected).await;
}
}
// A json number in scientific notation loads into a BIGINT UNSIGNED column with every digit,
// also when a `Float64` can't hold it.
#[apply(standalone_instance_case)]
async fn test_execute_copy_from_json_uint64_notation(instance: Arc<dyn MockInstance>) {
common_telemetry::init_default_ut_logging();
let instance = instance.frontend();
assert!(matches!(
execute_sql(
&instance,
"create table uint64_notation(k string, n bigint unsigned, ts timestamp time index, primary key(k));",
)
.await
.data,
OutputData::AffectedRows(0)
));
let filepath = find_testing_resource("/tests/data/json/uint64_notation.json");
let output = execute_sql(
&instance,
&format!("copy uint64_notation from '{filepath}' WITH(FORMAT='json');"),
)
.await
.data;
assert!(matches!(output, OutputData::AffectedRows(6)));
let output = execute_sql(&instance, "select k, n from uint64_notation order by k;")
.await
.data;
let expected = r#"+---+----------------------+
| k | n |
+---+----------------------+
| a | 9007199254740993 |
| b | 18446744073709551615 |
| c | 18446744073709551615 |
| d | 9007199254740993 |
| e | 7 |
| f | |
+---+----------------------+"#;
check_output_stream(output, expected).await;
}
// An empty json string is not a number. It fails to load into a DECIMAL column, also when the
// column was inferred as a number from the rows before it.
#[apply(standalone_instance_case)]
async fn test_execute_copy_from_json_decimal_empty_string(instance: Arc<dyn MockInstance>) {
common_telemetry::init_default_ut_logging();
let instance = instance.frontend();
assert!(matches!(
execute_sql(
&instance,
"create table decimal_empty_string(k string, price decimal(38, 2), ts timestamp time index, primary key(k));",
)
.await
.data,
OutputData::AffectedRows(0)
));
let filepath = find_testing_resource("/tests/data/json/decimal_empty_string.json");
let error = try_execute_sql(
&instance,
&format!(
"copy decimal_empty_string from '{filepath}' WITH(FORMAT='json', schema_infer_max_record=1);"
),
)
.await
.unwrap_err();
let error = format!("{error:?}");
assert!(
error.contains("can't parse the value as DECIMAL(38, 2)"),
"{error}"
);
let output = execute_sql(&instance, "select count(*) from decimal_empty_string;")
.await
.data;
let expected = r#"+----------+
| count(*) |
+----------+
| 0 |
+----------+"#;
check_output_stream(output, expected).await;
}
#[apply(standalone_instance_case)]
async fn test_execute_copy_from_orc(instance: Arc<dyn MockInstance>) {
common_telemetry::init_default_ut_logging();
@@ -0,0 +1,240 @@
-- COPY FROM keeps every digit of a DECIMAL or BIGINT UNSIGNED value from a csv or json file.
CREATE TABLE exact_decimals(k STRING, price DECIMAL(38, 10), amount DECIMAL(20, 2), ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Affected Rows: 0
INSERT INTO exact_decimals VALUES
('a', CAST('213865087984.2783187654' AS DECIMAL(38, 10)), CAST('123456789012345678.12' AS DECIMAL(20, 2)), 1000),
('b', CAST('0.1234567891' AS DECIMAL(38, 10)), CAST('-0.01' AS DECIMAL(20, 2)), 2000),
('c', CAST('-9999999999999999999999999999.9999999999' AS DECIMAL(38, 10)), CAST('7' AS DECIMAL(20, 2)), 3000),
('d', NULL, NULL, 4000);
Affected Rows: 4
Copy exact_decimals TO '${SQLNESS_HOME}/demo/export/exact_numbers/decimals.csv' WITH (format='csv');
Affected Rows: 4
CREATE TABLE exact_decimals_csv(k STRING, price DECIMAL(38, 10), amount DECIMAL(20, 2), ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Affected Rows: 0
Copy exact_decimals_csv FROM '${SQLNESS_HOME}/demo/export/exact_numbers/decimals.csv' WITH (format='csv');
Affected Rows: 4
SELECT k, CAST(price AS STRING) AS price, CAST(amount AS STRING) AS amount FROM exact_decimals_csv ORDER BY k;
+---+------------------------------------------+-----------------------+
| k | price | amount |
+---+------------------------------------------+-----------------------+
| a | 213865087984.2783187654 | 123456789012345678.12 |
| b | 0.1234567891 | -0.01 |
| c | -9999999999999999999999999999.9999999999 | 7.00 |
| d | | |
+---+------------------------------------------+-----------------------+
Copy exact_decimals TO '${SQLNESS_HOME}/demo/export/exact_numbers/decimals.json' WITH (format='json');
Affected Rows: 4
CREATE TABLE exact_decimals_json(k STRING, price DECIMAL(38, 10), amount DECIMAL(20, 2), ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Affected Rows: 0
Copy exact_decimals_json FROM '${SQLNESS_HOME}/demo/export/exact_numbers/decimals.json' WITH (format='json');
Affected Rows: 4
SELECT k, CAST(price AS STRING) AS price, CAST(amount AS STRING) AS amount FROM exact_decimals_json ORDER BY k;
+---+------------------------------------------+-----------------------+
| k | price | amount |
+---+------------------------------------------+-----------------------+
| a | 213865087984.2783187654 | 123456789012345678.12 |
| b | 0.1234567891 | -0.01 |
| c | -9999999999999999999999999999.9999999999 | 7.00 |
| d | | |
+---+------------------------------------------+-----------------------+
CREATE TABLE exact_integers(k STRING, u BIGINT UNSIGNED, i BIGINT, ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Affected Rows: 0
INSERT INTO exact_integers VALUES
('a', 9007199254740993, 9007199254740993, 1000),
('b', 18446744073709551615, 9223372036854775807, 2000),
('c', 1955706447374193284, 1955706447374193284, 3000),
('d', 0, -9223372036854775808, 4000),
('e', NULL, NULL, 5000);
Affected Rows: 5
Copy exact_integers TO '${SQLNESS_HOME}/demo/export/exact_numbers/integers.json' WITH (format='json');
Affected Rows: 5
CREATE TABLE exact_integers_json(k STRING, u BIGINT UNSIGNED, i BIGINT, ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Affected Rows: 0
Copy exact_integers_json FROM '${SQLNESS_HOME}/demo/export/exact_numbers/integers.json' WITH (format='json');
Affected Rows: 5
SELECT k, CAST(u AS STRING) AS u, CAST(i AS STRING) AS i FROM exact_integers_json ORDER BY k;
+---+----------------------+----------------------+
| k | u | i |
+---+----------------------+----------------------+
| a | 9007199254740993 | 9007199254740993 |
| b | 18446744073709551615 | 9223372036854775807 |
| c | 1955706447374193284 | 1955706447374193284 |
| d | 0 | -9223372036854775808 |
| e | | |
+---+----------------------+----------------------+
-- The value above the BIGINT range comes after the rows that schema inference reads.
CREATE TABLE exact_integers_late_json(k STRING, u BIGINT UNSIGNED, i BIGINT, ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Affected Rows: 0
Copy exact_integers_late_json FROM '${SQLNESS_HOME}/demo/export/exact_numbers/integers.json' WITH (format='json', schema_infer_max_record=1);
Affected Rows: 5
SELECT k, CAST(u AS STRING) AS u, CAST(i AS STRING) AS i FROM exact_integers_late_json ORDER BY k;
+---+----------------------+----------------------+
| k | u | i |
+---+----------------------+----------------------+
| a | 9007199254740993 | 9007199254740993 |
| b | 18446744073709551615 | 9223372036854775807 |
| c | 1955706447374193284 | 1955706447374193284 |
| d | 0 | -9223372036854775808 |
| e | | |
+---+----------------------+----------------------+
Copy exact_integers TO '${SQLNESS_HOME}/demo/export/exact_numbers/integers.csv' WITH (format='csv');
Affected Rows: 5
CREATE TABLE exact_integers_csv(k STRING, u BIGINT UNSIGNED, i BIGINT, ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Affected Rows: 0
Copy exact_integers_csv FROM '${SQLNESS_HOME}/demo/export/exact_numbers/integers.csv' WITH (format='csv');
Affected Rows: 5
SELECT k, CAST(u AS STRING) AS u, CAST(i AS STRING) AS i FROM exact_integers_csv ORDER BY k;
+---+----------------------+----------------------+
| k | u | i |
+---+----------------------+----------------------+
| a | 9007199254740993 | 9007199254740993 |
| b | 18446744073709551615 | 9223372036854775807 |
| c | 1955706447374193284 | 1955706447374193284 |
| d | 0 | -9223372036854775808 |
| e | | |
+---+----------------------+----------------------+
-- A value with more fractional digits than the column scale is rounded, not truncated.
CREATE TABLE rounded_decimals(k STRING, price DECIMAL(38, 12), amount DECIMAL(20, 4), ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Affected Rows: 0
INSERT INTO rounded_decimals VALUES
('a', CAST('1.123456789050' AS DECIMAL(38, 12)), CAST('1.0050' AS DECIMAL(20, 4)), 1000),
('b', CAST('-1.123456789050' AS DECIMAL(38, 12)), CAST('-1.0050' AS DECIMAL(20, 4)), 2000),
('c', CAST('0.123456789149' AS DECIMAL(38, 12)), CAST('2.9949' AS DECIMAL(20, 4)), 3000),
('d', CAST('7' AS DECIMAL(38, 12)), CAST('2.9950' AS DECIMAL(20, 4)), 4000);
Affected Rows: 4
Copy rounded_decimals TO '${SQLNESS_HOME}/demo/export/exact_numbers/rounded_decimals.csv' WITH (format='csv');
Affected Rows: 4
CREATE TABLE rounded_decimals_csv(k STRING, price DECIMAL(38, 10), amount DECIMAL(20, 2), ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Affected Rows: 0
Copy rounded_decimals_csv FROM '${SQLNESS_HOME}/demo/export/exact_numbers/rounded_decimals.csv' WITH (format='csv');
Affected Rows: 4
SELECT k, CAST(price AS STRING) AS price, CAST(amount AS STRING) AS amount FROM rounded_decimals_csv ORDER BY k;
+---+---------------+--------+
| k | price | amount |
+---+---------------+--------+
| a | 1.1234567891 | 1.01 |
| b | -1.1234567891 | -1.01 |
| c | 0.1234567891 | 2.99 |
| d | 7.0000000000 | 3.00 |
+---+---------------+--------+
Copy rounded_decimals TO '${SQLNESS_HOME}/demo/export/exact_numbers/rounded_decimals.json' WITH (format='json');
Affected Rows: 4
CREATE TABLE rounded_decimals_json(k STRING, price DECIMAL(38, 10), amount DECIMAL(20, 2), ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Affected Rows: 0
Copy rounded_decimals_json FROM '${SQLNESS_HOME}/demo/export/exact_numbers/rounded_decimals.json' WITH (format='json');
Affected Rows: 4
SELECT k, CAST(price AS STRING) AS price, CAST(amount AS STRING) AS amount FROM rounded_decimals_json ORDER BY k;
+---+---------------+--------+
| k | price | amount |
+---+---------------+--------+
| a | 1.1234567891 | 1.01 |
| b | -1.1234567891 | -1.01 |
| c | 0.1234567891 | 2.99 |
| d | 7.0000000000 | 3.00 |
+---+---------------+--------+
DROP TABLE exact_decimals;
Affected Rows: 0
DROP TABLE exact_decimals_csv;
Affected Rows: 0
DROP TABLE exact_decimals_json;
Affected Rows: 0
DROP TABLE exact_integers;
Affected Rows: 0
DROP TABLE exact_integers_csv;
Affected Rows: 0
DROP TABLE exact_integers_json;
Affected Rows: 0
DROP TABLE exact_integers_late_json;
Affected Rows: 0
DROP TABLE rounded_decimals;
Affected Rows: 0
DROP TABLE rounded_decimals_csv;
Affected Rows: 0
DROP TABLE rounded_decimals_json;
Affected Rows: 0
@@ -0,0 +1,101 @@
-- COPY FROM keeps every digit of a DECIMAL or BIGINT UNSIGNED value from a csv or json file.
CREATE TABLE exact_decimals(k STRING, price DECIMAL(38, 10), amount DECIMAL(20, 2), ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
INSERT INTO exact_decimals VALUES
('a', CAST('213865087984.2783187654' AS DECIMAL(38, 10)), CAST('123456789012345678.12' AS DECIMAL(20, 2)), 1000),
('b', CAST('0.1234567891' AS DECIMAL(38, 10)), CAST('-0.01' AS DECIMAL(20, 2)), 2000),
('c', CAST('-9999999999999999999999999999.9999999999' AS DECIMAL(38, 10)), CAST('7' AS DECIMAL(20, 2)), 3000),
('d', NULL, NULL, 4000);
Copy exact_decimals TO '${SQLNESS_HOME}/demo/export/exact_numbers/decimals.csv' WITH (format='csv');
CREATE TABLE exact_decimals_csv(k STRING, price DECIMAL(38, 10), amount DECIMAL(20, 2), ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Copy exact_decimals_csv FROM '${SQLNESS_HOME}/demo/export/exact_numbers/decimals.csv' WITH (format='csv');
SELECT k, CAST(price AS STRING) AS price, CAST(amount AS STRING) AS amount FROM exact_decimals_csv ORDER BY k;
Copy exact_decimals TO '${SQLNESS_HOME}/demo/export/exact_numbers/decimals.json' WITH (format='json');
CREATE TABLE exact_decimals_json(k STRING, price DECIMAL(38, 10), amount DECIMAL(20, 2), ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Copy exact_decimals_json FROM '${SQLNESS_HOME}/demo/export/exact_numbers/decimals.json' WITH (format='json');
SELECT k, CAST(price AS STRING) AS price, CAST(amount AS STRING) AS amount FROM exact_decimals_json ORDER BY k;
CREATE TABLE exact_integers(k STRING, u BIGINT UNSIGNED, i BIGINT, ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
INSERT INTO exact_integers VALUES
('a', 9007199254740993, 9007199254740993, 1000),
('b', 18446744073709551615, 9223372036854775807, 2000),
('c', 1955706447374193284, 1955706447374193284, 3000),
('d', 0, -9223372036854775808, 4000),
('e', NULL, NULL, 5000);
Copy exact_integers TO '${SQLNESS_HOME}/demo/export/exact_numbers/integers.json' WITH (format='json');
CREATE TABLE exact_integers_json(k STRING, u BIGINT UNSIGNED, i BIGINT, ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Copy exact_integers_json FROM '${SQLNESS_HOME}/demo/export/exact_numbers/integers.json' WITH (format='json');
SELECT k, CAST(u AS STRING) AS u, CAST(i AS STRING) AS i FROM exact_integers_json ORDER BY k;
-- The value above the BIGINT range comes after the rows that schema inference reads.
CREATE TABLE exact_integers_late_json(k STRING, u BIGINT UNSIGNED, i BIGINT, ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Copy exact_integers_late_json FROM '${SQLNESS_HOME}/demo/export/exact_numbers/integers.json' WITH (format='json', schema_infer_max_record=1);
SELECT k, CAST(u AS STRING) AS u, CAST(i AS STRING) AS i FROM exact_integers_late_json ORDER BY k;
Copy exact_integers TO '${SQLNESS_HOME}/demo/export/exact_numbers/integers.csv' WITH (format='csv');
CREATE TABLE exact_integers_csv(k STRING, u BIGINT UNSIGNED, i BIGINT, ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Copy exact_integers_csv FROM '${SQLNESS_HOME}/demo/export/exact_numbers/integers.csv' WITH (format='csv');
SELECT k, CAST(u AS STRING) AS u, CAST(i AS STRING) AS i FROM exact_integers_csv ORDER BY k;
-- A value with more fractional digits than the column scale is rounded, not truncated.
CREATE TABLE rounded_decimals(k STRING, price DECIMAL(38, 12), amount DECIMAL(20, 4), ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
INSERT INTO rounded_decimals VALUES
('a', CAST('1.123456789050' AS DECIMAL(38, 12)), CAST('1.0050' AS DECIMAL(20, 4)), 1000),
('b', CAST('-1.123456789050' AS DECIMAL(38, 12)), CAST('-1.0050' AS DECIMAL(20, 4)), 2000),
('c', CAST('0.123456789149' AS DECIMAL(38, 12)), CAST('2.9949' AS DECIMAL(20, 4)), 3000),
('d', CAST('7' AS DECIMAL(38, 12)), CAST('2.9950' AS DECIMAL(20, 4)), 4000);
Copy rounded_decimals TO '${SQLNESS_HOME}/demo/export/exact_numbers/rounded_decimals.csv' WITH (format='csv');
CREATE TABLE rounded_decimals_csv(k STRING, price DECIMAL(38, 10), amount DECIMAL(20, 2), ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Copy rounded_decimals_csv FROM '${SQLNESS_HOME}/demo/export/exact_numbers/rounded_decimals.csv' WITH (format='csv');
SELECT k, CAST(price AS STRING) AS price, CAST(amount AS STRING) AS amount FROM rounded_decimals_csv ORDER BY k;
Copy rounded_decimals TO '${SQLNESS_HOME}/demo/export/exact_numbers/rounded_decimals.json' WITH (format='json');
CREATE TABLE rounded_decimals_json(k STRING, price DECIMAL(38, 10), amount DECIMAL(20, 2), ts TIMESTAMP TIME INDEX, PRIMARY KEY(k));
Copy rounded_decimals_json FROM '${SQLNESS_HOME}/demo/export/exact_numbers/rounded_decimals.json' WITH (format='json');
SELECT k, CAST(price AS STRING) AS price, CAST(amount AS STRING) AS amount FROM rounded_decimals_json ORDER BY k;
DROP TABLE exact_decimals;
DROP TABLE exact_decimals_csv;
DROP TABLE exact_decimals_json;
DROP TABLE exact_integers;
DROP TABLE exact_integers_csv;
DROP TABLE exact_integers_json;
DROP TABLE exact_integers_late_json;
DROP TABLE rounded_decimals;
DROP TABLE rounded_decimals_csv;
DROP TABLE rounded_decimals_json;
+8
View File
@@ -0,0 +1,8 @@
k,price,ts
a,1.2500000000000000000000000000000000000000e0,1000
b,0e0,2000
c,12345e-3,3000
d,1.005,4000
e,-1.005,5000
f,123456789012345678901234567890123456.78,6000
g,,7000
1 k price ts
2 a 1.2500000000000000000000000000000000000000e0 1000
3 b 0e0 2000
4 c 12345e-3 3000
5 d 1.005 4000
6 e -1.005 5000
7 f 123456789012345678901234567890123456.78 6000
8 g 7000
@@ -0,0 +1,2 @@
{"k":"a","price":1.25,"ts":1000}
{"k":"b","price":"","ts":2000}
+7
View File
@@ -0,0 +1,7 @@
{"k":"a","price":1.2500000000000000000000000000000000000000e0,"ts":1000}
{"k":"b","price":0e0,"ts":2000}
{"k":"c","price":12345e-3,"ts":3000}
{"k":"d","price":1.005,"ts":4000}
{"k":"e","price":-1.005,"ts":5000}
{"k":"f","price":123456789012345678901234567890123456.78,"ts":6000}
{"k":"g","price":null,"ts":7000}
+6
View File
@@ -0,0 +1,6 @@
{"k":"a","n":9007199254740993e0,"ts":1000}
{"k":"b","n":18446744073709551615,"ts":2000}
{"k":"c","n":1.8446744073709551615e19,"ts":3000}
{"k":"d","n":9007199254740993.0,"ts":4000}
{"k":"e","n":7,"ts":5000}
{"k":"f","n":null,"ts":6000}