This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-12871-3f78e15099679252efc6dc6cbcba770a671e0acf in repository https://gitbox.apache.org/repos/asf/seatunnel.git
commit 310913d494661cef133e5e9c593cafdac9bb41bd Author: Tiefang Hu <[email protected]> AuthorDate: Sat Nov 7 06:41:22 2026 +0000 [Fix][Format] Preserve JSON decimal precision inside arrays (#12871) Signed-off-by: hutiefang76 <[email protected]> --- docs/en/connectors/formats/overview.md | 4 + .../introduction/concepts/incompatible-changes.md | 6 + docs/zh/connectors/formats/overview.md | 4 + .../introduction/concepts/incompatible-changes.md | 6 + .../format/json/JsonDeserializationSchema.java | 12 + .../format/json/JsonRowDataSerDeSchemaTest.java | 361 +++++++++++++++++++++ 6 files changed, 393 insertions(+) diff --git a/docs/en/connectors/formats/overview.md b/docs/en/connectors/formats/overview.md index 3153b525ec3..53f0e65cf6d 100644 --- a/docs/en/connectors/formats/overview.md +++ b/docs/en/connectors/formats/overview.md @@ -13,6 +13,10 @@ Format docs explain how SeaTunnel maps between its internal row model and extern - your CDC pipeline depends on a specific envelope format - you need to align external serialization with downstream consumers +## DECIMAL Precision in JSON + +When a schema declares a `DECIMAL` field, including one nested in an array, the JSON reader parses floating-point numbers as `BigDecimal` to avoid losing numeric precision. This covers `ARRAY<DECIMAL>`, `ARRAY<ARRAY<DECIMAL>>` and `ARRAY<ROW<DECIMAL>>`. The setting applies to the whole document: a bare floating-point number assigned to a `STRING` sibling is rendered from its decimal value and may retain more digits. It does not preserve the original token spelling; for example, `0.000000 [...] + ## Useful Next Pages - [Data Format Handling](../../architecture/data-format-handling.md) diff --git a/docs/en/introduction/concepts/incompatible-changes.md b/docs/en/introduction/concepts/incompatible-changes.md index a8a691be11d..7fea5d0f77f 100644 --- a/docs/en/introduction/concepts/incompatible-changes.md +++ b/docs/en/introduction/concepts/incompatible-changes.md @@ -517,6 +517,12 @@ or state format migration is required. - **Description**: Previously, a field declared as a numeric type in the catalog (`TINYINT`, `SMALLINT`, `INT`, `BIGINT`, `FLOAT`, `DOUBLE`, `DECIMAL`) was serialized by blindly casting the runtime value to the Java type implied by the declared type (for example `(long) value` for `BIGINT`). In multi-table jobs (for example CDC jobs writing JSON to RabbitMQ/Kafka) where several tables share one catalog schema but carry different physical column types, a `String` or `BigDecimal` runtime [...] - **Impact**: Heterogeneous numeric values that previously crashed the job with `ClassCastException` now serialize successfully, and the emitted JSON numeric shape follows the runtime value rather than the declared column type (a `String` or `BigDecimal` value in a `BIGINT` column keeps its exact numeric value). Runtime values that can neither be represented as a number nor parsed from text (for example `byte[]`, `Map`, `LocalDateTime`) now fail fast with a typed `SeaTunnelJsonFormatEx [...] +- **Behavior change: JSON deserialization keeps the precision of `DECIMAL` values nested in arrays** + - **Affected component**: `seatunnel-formats/seatunnel-format-json` (`JsonDeserializationSchema`) - affects every connector that reads rows with the JSON format (for example Kafka, RabbitMQ, Pulsar, and file JSON sources) + - **Description**: A `DECIMAL` declared inside an `ARRAY` (for example `ARRAY<DECIMAL>`, `ARRAY<ARRAY<DECIMAL>>` or `ARRAY<ROW<DECIMAL>>`) was not found when deciding whether the numbers of a document must be parsed as `BigDecimal`, because an array is not a composite type. Its elements were parsed as `double` first and converted to `DECIMAL` afterwards, so they lost every digit beyond `double` precision, while a scalar `DECIMAL` column of the same schema kept them. A `DECIMAL` nested [...] + - **Impact**: Elements of a declared `DECIMAL` array are no longer rounded to about 17 significant digits. Since the underlying mapper setting applies to the whole document, in a schema that declares a `DECIMAL` inside an array a bare number assigned to a `STRING` field now keeps all of its digits (`3.14159265358979323846` instead of `3.141592653589793`). The same happens to floating-point numbers nested inside a JSON object or array that a `STRING` field captures as text: the object o [...] + - **Migration Guide**: If a downstream step compares the text of such numeric values, review those comparisons against the exact digits, or make the source provide quoted JSON strings for `STRING` columns that carry bare numbers. JSON objects or arrays stored in a `STRING` column belong to the same category: compare their serialized text (digits and exponent notation) before relying on it, or have the source send those values as quoted JSON strings. `DECIMAL` columns require no configu [...] + ### Engine Behavior Changes - **File-based IMap storage: legacy job model class names in WAL files are remapped on startup** diff --git a/docs/zh/connectors/formats/overview.md b/docs/zh/connectors/formats/overview.md index b7148995c63..43832985a8c 100644 --- a/docs/zh/connectors/formats/overview.md +++ b/docs/zh/connectors/formats/overview.md @@ -13,6 +13,10 @@ sidebar_position: 1 - CDC 链路依赖特定的 envelope 格式 - 需要让外部序列化格式与下游消费方保持一致 +## JSON 中的 DECIMAL 精度 + +当 Schema 中声明了 `DECIMAL` 字段(包括数组中的嵌套字段)时,JSON 读取器会按 `BigDecimal` 解析浮点数,避免丢失数值精度。支持的类型包括 `ARRAY<DECIMAL>`、`ARRAY<ARRAY<DECIMAL>>` 和 `ARRAY<ROW<DECIMAL>>`。该设置作用于整个文档:同一 Schema 中赋给 `STRING` 字段的裸浮点数会根据十进制数值重新生成文本,可能保留更多位数,但不保证原始写法不变,例如 `0.0000001234` 可能变为 `1.234E-7`。作为文本赋给 `STRING` 字段的 JSON 对象或数组同理:其中的浮点数同样按十进制值重新生成文本,因此文本也可能变化;而这些对象或数组内部带引号的数字仍保持原始文本。带引号的字符串以及不含 `DECIMAL` 的 Schema 保持原有行为。 + ## 常用下一步 - [数据格式处理](../../architecture/data-format-handling.md) diff --git a/docs/zh/introduction/concepts/incompatible-changes.md b/docs/zh/introduction/concepts/incompatible-changes.md index 8583a25b9df..d205cac061a 100644 --- a/docs/zh/introduction/concepts/incompatible-changes.md +++ b/docs/zh/introduction/concepts/incompatible-changes.md @@ -437,6 +437,12 @@ Zeta SQL ARRAY 函数现在将 TINYINT 元素声明为 `ARRAY<TINYINT>`,与实 - **变更说明**:以前,目录 Schema 中声明为数值类型(`TINYINT`、`SMALLINT`、`INT`、`BIGINT`、`FLOAT`、`DOUBLE`、`DECIMAL`)的字段,序列化时会把运行时值强制转换为声明类型对应的 Java 类型(例如 `BIGINT` 直接 `(long) value`)。在多表作业(例如多表 CDC 作业写 JSON 到 RabbitMQ/Kafka)中,多张表共享同一份目录 Schema 但物理列类型不一致时,`String` 或 `BigDecimal` 运行时值会抛出原始 `ClassCastException` 并导致作业失败。现在数值字段按运行时实际类型序列化:任意数值包装类型(`Byte`、`Short`、`Integer`、`Long`、`Float`、`Double`、`BigInteger`、`BigDecimal`)输出为对应的 JSON 数字;可解析为数字的字符串会解析成 JSON 数字,无法解析的文本则输出为 JSON 字符串;声明为 `DECIMAL` 的字段遇到 `Float`/`Dou [...] - **影响**:以前因 `ClassCastException` 崩溃的异构数值现在可以正常序列化,输出的 JSON 数值形态跟随运行时值而非声明的列类型(`BIGINT` 列中的 `String` 或 `BigDecimal` 值会保留其精确数值)。既不能表示为数字、也无法从文本解析的运行时值(例如 `byte[]`、`Map`、`LocalDateTime`)将以类型化的 `SeaTunnelJsonFormatException`(`UNSUPPORTED_DATA_TYPE`)快速失败,替代原来的原始 `ClassCastException`。假定 JSON 数值形态始终与声明列类型一致的下游消费方需要重新评估。(#11415) +- **行为变更:JSON 反序列化保留嵌套在数组中的 `DECIMAL` 精度** + - **影响范围**:`seatunnel-formats/seatunnel-format-json`(`JsonDeserializationSchema`)--影响所有以 JSON 格式读取行的连接器(例如 Kafka、RabbitMQ、Pulsar 及文件 JSON Source)。 + - **变更说明**:判断是否需要把文档中的数字按 `BigDecimal` 解析时,此前不会发现声明在 `ARRAY` 中的 `DECIMAL`(例如 `ARRAY<DECIMAL>`、`ARRAY<ARRAY<DECIMAL>>` 或 `ARRAY<ROW<DECIMAL>>`),因为数组不是复合类型。其元素会先按 `double` 解析,随后才转换为 `DECIMAL`,因此会丢失 `double` 精度之外的各位数字,而同一 Schema 中的标量 `DECIMAL` 列却能保留。现在嵌套在数组中的 `DECIMAL` 与标量 `DECIMAL` 一样保留数值精度。选项、默认值和行结构均未变化。 + - **影响**:声明为 `DECIMAL` 的数组元素不再被舍入到约 17 位有效数字。由于底层的 mapper 设置作用于整个文档,在声明了数组内 `DECIMAL` 的 Schema 中,赋给 `STRING` 字段的裸数字现在会保留全部数位(`3.14159265358979323846`,此前为 `3.141592653589793`)。作为文本赋给 `STRING` 字段的 JSON 对象或数组同理:容器会按十进制值重新生成文本,其中的浮点数可能保留更多位数或改用指数表示(`1e-10` 会变为 `1E-10`),而同一对象或数组内以引号包裹的数字仍保持原始文本。带引号的 JSON 字符串以及不含任何 `DECIMAL` 的 Schema 不受影响。 (#12871) + - **迁移指南**:如果下游环节会比较这类数值的文本,请按精确数位重新评估这些比较逻辑,或让来源为承载裸数字的 `STRING` 列提供带引号的 JSON 字符串。存放在 `STRING` 列中的 JSON 对象或数组也属于同一类:请先核对它们序列化后的文本(数位与指数写法)再依赖该文本,或让来源以带引号的 JSON 字符串提供这些值。`DECIMAL` 列无需修改配置即可保留声明的数值精度。 + ### 引擎行为变更 - **文件型 IMap 存储:启动时自动重映射 WAL 文件中的旧版作业模型类名** diff --git a/seatunnel-formats/seatunnel-format-json/src/main/java/org/apache/seatunnel/format/json/JsonDeserializationSchema.java b/seatunnel-formats/seatunnel-format-json/src/main/java/org/apache/seatunnel/format/json/JsonDeserializationSchema.java index a07e2b41657..3d293bda389 100644 --- a/seatunnel-formats/seatunnel-format-json/src/main/java/org/apache/seatunnel/format/json/JsonDeserializationSchema.java +++ b/seatunnel-formats/seatunnel-format-json/src/main/java/org/apache/seatunnel/format/json/JsonDeserializationSchema.java @@ -30,6 +30,7 @@ import org.apache.seatunnel.api.serialization.DeserializationSchema; import org.apache.seatunnel.api.source.Collector; import org.apache.seatunnel.api.table.catalog.CatalogTable; import org.apache.seatunnel.api.table.catalog.TablePath; +import org.apache.seatunnel.api.table.type.ArrayType; import org.apache.seatunnel.api.table.type.CompositeType; import org.apache.seatunnel.api.table.type.SeaTunnelDataType; import org.apache.seatunnel.api.table.type.SeaTunnelRow; @@ -109,10 +110,21 @@ public class JsonDeserializationSchema implements DeserializationSchema<SeaTunne objectMapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true); } + /** + * Checks whether a DECIMAL type is reachable from {@code dataType}, so that floating-point JSON + * numbers can be parsed as {@link java.math.BigDecimal} and keep their precision. + * + * @param dataType declared type of a column or of a nested element/field + * @return true if {@code dataType} is DECIMAL or contains a DECIMAL somewhere below it + */ private static boolean hasDecimalType(SeaTunnelDataType<?> dataType) { if (dataType.getSqlType() == SqlType.DECIMAL) { return true; } + // ArrayType is not a CompositeType, so its elements have to be visited explicitly. + if (dataType instanceof ArrayType) { + return hasDecimalType(((ArrayType<?, ?>) dataType).getElementType()); + } if (dataType instanceof CompositeType) { CompositeType<?> compositeType = (CompositeType<?>) dataType; for (SeaTunnelDataType<?> child : compositeType.getChildren()) { diff --git a/seatunnel-formats/seatunnel-format-json/src/test/java/org/apache/seatunnel/format/json/JsonRowDataSerDeSchemaTest.java b/seatunnel-formats/seatunnel-format-json/src/test/java/org/apache/seatunnel/format/json/JsonRowDataSerDeSchemaTest.java index 8e333dd777b..058f9613cfe 100644 --- a/seatunnel-formats/seatunnel-format-json/src/test/java/org/apache/seatunnel/format/json/JsonRowDataSerDeSchemaTest.java +++ b/seatunnel-formats/seatunnel-format-json/src/test/java/org/apache/seatunnel/format/json/JsonRowDataSerDeSchemaTest.java @@ -58,6 +58,7 @@ import java.util.HashMap; import java.util.Map; import java.util.TimeZone; +import static org.apache.seatunnel.api.table.type.ArrayType.DOUBLE_ARRAY_TYPE; import static org.apache.seatunnel.api.table.type.ArrayType.INT_ARRAY_TYPE; import static org.apache.seatunnel.api.table.type.ArrayType.STRING_ARRAY_TYPE; import static org.apache.seatunnel.api.table.type.BasicType.BOOLEAN_TYPE; @@ -77,6 +78,12 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class JsonRowDataSerDeSchemaTest { + /** + * A literal with 20 fraction digits, i.e. more digits than a {@code double} can represent. It + * only survives the JSON parse intact when the mapper parses floats as {@link BigDecimal}. + */ + private static final String HIGH_PRECISION_DECIMAL_LITERAL = "3.14159265358979323846"; + private static final SeaTunnelRowType CONTAINER_ARRAY_ROW_TYPE = new SeaTunnelRowType( new String[] {"id", "arr"}, @@ -977,6 +984,360 @@ public class JsonRowDataSerDeSchemaTest { fractionalPrecisionRow.getField(0)); } + @Test + public void testDeserializeHighPrecisionScalarDecimalKeepsExactValue() throws IOException { + // Scalar and nested DECIMAL values must preserve the same fractional digits. + SeaTunnelRowType rowType = + new SeaTunnelRowType( + new String[] {"amount"}, + new SeaTunnelDataType<?>[] {new DecimalType(38, 20)}); + JsonDeserializationSchema deserializationSchema = + new JsonDeserializationSchema(false, false, rowType); + + SeaTunnelRow row = + deserializationSchema.deserialize( + ("{\"amount\":" + HIGH_PRECISION_DECIMAL_LITERAL + "}") + .getBytes(StandardCharsets.UTF_8)); + + assertEquals( + 0, + new BigDecimal(HIGH_PRECISION_DECIMAL_LITERAL) + .compareTo((BigDecimal) row.getField(0)), + "scalar DECIMAL must keep the exact input precision"); + } + + @Test + public void testDeserializeHighPrecisionDecimalArrayKeepsExactValue() throws IOException { + SeaTunnelRowType rowType = + new SeaTunnelRowType( + new String[] {"amounts"}, + new SeaTunnelDataType<?>[] { + ArrayType.of(new DecimalType(38, 20)), + }); + JsonDeserializationSchema deserializationSchema = + new JsonDeserializationSchema(false, false, rowType); + + SeaTunnelRow row = + deserializationSchema.deserialize( + ("{\"amounts\":[" + HIGH_PRECISION_DECIMAL_LITERAL + "]}") + .getBytes(StandardCharsets.UTF_8)); + + BigDecimal[] amounts = (BigDecimal[]) row.getField(0); + assertEquals( + 0, + new BigDecimal(HIGH_PRECISION_DECIMAL_LITERAL).compareTo(amounts[0]), + "DECIMAL element of ARRAY<DECIMAL> must keep the exact input precision"); + } + + @Test + public void testDeserializeHighPrecisionDecimalNestedArrayKeepsExactValue() throws IOException { + SeaTunnelRowType rowType = + new SeaTunnelRowType( + new String[] {"matrix"}, + new SeaTunnelDataType<?>[] { + ArrayType.of(ArrayType.of(new DecimalType(38, 20))), + }); + JsonDeserializationSchema deserializationSchema = + new JsonDeserializationSchema(false, false, rowType); + + SeaTunnelRow row = + deserializationSchema.deserialize( + "{\"matrix\":[[1.23456789012345678901]]}".getBytes(StandardCharsets.UTF_8)); + + BigDecimal[][] matrix = (BigDecimal[][]) row.getField(0); + assertEquals( + 0, + new BigDecimal("1.23456789012345678901").compareTo(matrix[0][0]), + "DECIMAL element of ARRAY<ARRAY<DECIMAL>> must keep the exact input precision"); + } + + @Test + public void testDeserializeHighPrecisionDecimalRowInArrayKeepsExactValue() throws IOException { + SeaTunnelRowType elementRowType = + new SeaTunnelRowType( + new String[] {"amount"}, + new SeaTunnelDataType<?>[] {new DecimalType(38, 20)}); + SeaTunnelRowType rowType = + new SeaTunnelRowType( + new String[] {"entries"}, + new SeaTunnelDataType<?>[] {ArrayType.of(elementRowType)}); + JsonDeserializationSchema deserializationSchema = + new JsonDeserializationSchema(false, false, rowType); + + SeaTunnelRow row = + deserializationSchema.deserialize( + "{\"entries\":[{\"amount\":9.87654321098765432109}]}" + .getBytes(StandardCharsets.UTF_8)); + + SeaTunnelRow[] entries = (SeaTunnelRow[]) row.getField(0); + assertEquals( + 0, + new BigDecimal("9.87654321098765432109") + .compareTo((BigDecimal) entries[0].getField(0)), + "DECIMAL field of ROW inside ARRAY<ROW<DECIMAL>> must keep the exact precision"); + } + + @Test + public void testDeserializeHighPrecisionDecimalArrayWithScalarDecimalSibling() + throws IOException { + // Adding a scalar DECIMAL sibling must not change the precision of array elements. + SeaTunnelRowType rowType = + new SeaTunnelRowType( + new String[] {"amount", "amounts"}, + new SeaTunnelDataType<?>[] { + new DecimalType(38, 20), ArrayType.of(new DecimalType(38, 20)), + }); + JsonDeserializationSchema deserializationSchema = + new JsonDeserializationSchema(false, false, rowType); + + SeaTunnelRow row = + deserializationSchema.deserialize( + ("{\"amount\":" + + HIGH_PRECISION_DECIMAL_LITERAL + + ",\"amounts\":[" + + HIGH_PRECISION_DECIMAL_LITERAL + + "]}") + .getBytes(StandardCharsets.UTF_8)); + + BigDecimal expected = new BigDecimal(HIGH_PRECISION_DECIMAL_LITERAL); + assertEquals(0, expected.compareTo((BigDecimal) row.getField(0))); + assertEquals(0, expected.compareTo(((BigDecimal[]) row.getField(1))[0])); + } + + @Test + public void testDeserializeNonDecimalArraysControl() throws IOException { + // Control: without any DECIMAL column the mapper keeps its default configuration and the + // non decimal array values must be unchanged. + SeaTunnelRowType rowType = + new SeaTunnelRowType( + new String[] {"ints", "doubles", "labels"}, + new SeaTunnelDataType<?>[] { + INT_ARRAY_TYPE, DOUBLE_ARRAY_TYPE, STRING_ARRAY_TYPE, + }); + JsonDeserializationSchema deserializationSchema = + new JsonDeserializationSchema(false, false, rowType); + + SeaTunnelRow row = + deserializationSchema.deserialize( + "{\"ints\":[1,2,3],\"doubles\":[1.5,2.25],\"labels\":[\"a\",\"b\"]}" + .getBytes(StandardCharsets.UTF_8)); + + assertArrayEquals(new Integer[] {1, 2, 3}, (Integer[]) row.getField(0)); + assertArrayEquals(new Double[] {1.5, 2.25}, (Double[]) row.getField(1)); + assertArrayEquals(new String[] {"a", "b"}, (String[]) row.getField(2)); + } + + @Test + public void testStringFieldAlongsideScalarDecimalUsesExactNumericText() throws IOException { + // Documents the global nature of USE_BIG_DECIMAL_FOR_FLOATS: once any DECIMAL enables it, a + // STRING field that carries a bare numeric token is rendered from the BigDecimal node. + SeaTunnelRowType rowType = + new SeaTunnelRowType( + new String[] {"amount", "label"}, + new SeaTunnelDataType<?>[] {new DecimalType(38, 20), STRING_TYPE}); + JsonDeserializationSchema deserializationSchema = + new JsonDeserializationSchema(false, false, rowType); + + SeaTunnelRow row = + deserializationSchema.deserialize( + ("{\"amount\":" + + HIGH_PRECISION_DECIMAL_LITERAL + + ",\"label\":" + + HIGH_PRECISION_DECIMAL_LITERAL + + "}") + .getBytes(StandardCharsets.UTF_8)); + + assertEquals(HIGH_PRECISION_DECIMAL_LITERAL, row.getField(1)); + } + + @Test + public void testStringFieldAlongsideDecimalArrayKeepsExactNumericText() throws IOException { + // The document-wide decimal parser also formats numeric STRING fields; + // quoted strings retain their original text. + SeaTunnelRowType rowType = + new SeaTunnelRowType( + new String[] {"amounts", "label"}, + new SeaTunnelDataType<?>[] { + ArrayType.of(new DecimalType(38, 20)), STRING_TYPE, + }); + JsonDeserializationSchema deserializationSchema = + new JsonDeserializationSchema(false, false, rowType); + + SeaTunnelRow bareNumberRow = + deserializationSchema.deserialize( + ("{\"amounts\":[1.5],\"label\":" + HIGH_PRECISION_DECIMAL_LITERAL + "}") + .getBytes(StandardCharsets.UTF_8)); + + assertEquals( + 0, + new BigDecimal("1.5").compareTo(((BigDecimal[]) bareNumberRow.getField(0))[0]), + "the DECIMAL element keeps its exact value"); + assertEquals( + HIGH_PRECISION_DECIMAL_LITERAL, + bareNumberRow.getField(1), + "a bare number in a STRING sibling keeps the exact numeric text"); + + // A quoted string is never re-rendered from a numeric node, so it stays untouched. + SeaTunnelRow quotedRow = + deserializationSchema.deserialize( + ("{\"amounts\":[1.5],\"label\":\"" + HIGH_PRECISION_DECIMAL_LITERAL + "\"}") + .getBytes(StandardCharsets.UTF_8)); + assertEquals(HIGH_PRECISION_DECIMAL_LITERAL, quotedRow.getField(1)); + + // Control: a schema without any DECIMAL keeps the default mapper configuration. + JsonDeserializationSchema noDecimalSchema = + new JsonDeserializationSchema( + false, + false, + new SeaTunnelRowType( + new String[] {"label"}, new SeaTunnelDataType<?>[] {STRING_TYPE})); + assertEquals( + "1.5", + noDecimalSchema + .deserialize("{\"label\":1.5}".getBytes(StandardCharsets.UTF_8)) + .getField(0)); + } + + @Test + public void testStringObjectAlongsideDecimalArrayKeepsNestedDigits() throws IOException { + // A JSON object captured as STRING is rendered from its nodes, so the document-wide decimal + // parser also keeps every digit of the numbers nested in it, both in nested objects and in + // nested arrays. + SeaTunnelRowType rowType = + new SeaTunnelRowType( + new String[] {"amounts", "raw"}, + new SeaTunnelDataType<?>[] { + ArrayType.of(new DecimalType(38, 20)), STRING_TYPE, + }); + JsonDeserializationSchema deserializationSchema = + new JsonDeserializationSchema(false, false, rowType); + + SeaTunnelRow row = + deserializationSchema.deserialize( + ("{\"amounts\":[" + + HIGH_PRECISION_DECIMAL_LITERAL + + "],\"raw\":{\"pi\":" + + HIGH_PRECISION_DECIMAL_LITERAL + + ",\"history\":[" + + HIGH_PRECISION_DECIMAL_LITERAL + + "],\"quoted\":\"1e-10\"}}") + .getBytes(StandardCharsets.UTF_8)); + + assertEquals( + 0, + new BigDecimal(HIGH_PRECISION_DECIMAL_LITERAL) + .compareTo(((BigDecimal[]) row.getField(0))[0]), + "the DECIMAL element keeps its exact value"); + assertEquals( + "{\"pi\":" + + HIGH_PRECISION_DECIMAL_LITERAL + + ",\"history\":[" + + HIGH_PRECISION_DECIMAL_LITERAL + + "],\"quoted\":\"1e-10\"}", + row.getField(1), + "an object captured as STRING keeps every digit of its nested numbers"); + } + + @Test + public void testStringArrayAlongsideDecimalArrayKeepsNestedDigits() throws IOException { + // A JSON array captured as STRING is rendered from its nodes as well. Small exponents are + // re-rendered in exponent notation: the decimal value of 1e-10 is written as 1E-10, whereas + // the double parser would write 1.0E-10. + SeaTunnelRowType rowType = + new SeaTunnelRowType( + new String[] {"amounts", "raw"}, + new SeaTunnelDataType<?>[] { + ArrayType.of(new DecimalType(38, 20)), STRING_TYPE, + }); + JsonDeserializationSchema deserializationSchema = + new JsonDeserializationSchema(false, false, rowType); + + SeaTunnelRow row = + deserializationSchema.deserialize( + ("{\"amounts\":[1e-10," + + HIGH_PRECISION_DECIMAL_LITERAL + + "],\"raw\":[1e-10,{\"pi\":" + + HIGH_PRECISION_DECIMAL_LITERAL + + "},\"1e-10\"]}") + .getBytes(StandardCharsets.UTF_8)); + + BigDecimal[] amounts = (BigDecimal[]) row.getField(0); + assertEquals( + 0, + new BigDecimal("1e-10").compareTo(amounts[0]), + "the small exponent keeps its exact decimal value"); + assertEquals( + 0, + new BigDecimal(HIGH_PRECISION_DECIMAL_LITERAL).compareTo(amounts[1]), + "the high precision element keeps every digit"); + assertEquals( + "[1E-10,{\"pi\":" + HIGH_PRECISION_DECIMAL_LITERAL + "},\"1e-10\"]", + row.getField(1), + "an array captured as STRING keeps the decimal rendering of its numbers"); + } + + @Test + public void testStringContainersWithoutDecimalKeepDoubleRendering() throws IOException { + // Control: without any DECIMAL column the mapper keeps parsing floats as double, so a JSON + // object or array captured as STRING keeps the double rendering it had before this fix. + SeaTunnelRowType rowType = + new SeaTunnelRowType( + new String[] {"doubles", "raw_object", "raw_array"}, + new SeaTunnelDataType<?>[] { + DOUBLE_ARRAY_TYPE, STRING_TYPE, STRING_TYPE, + }); + JsonDeserializationSchema deserializationSchema = + new JsonDeserializationSchema(false, false, rowType); + + SeaTunnelRow row = + deserializationSchema.deserialize( + ("{\"doubles\":[1.5,2.25],\"raw_object\":{\"pi\":" + + HIGH_PRECISION_DECIMAL_LITERAL + + "},\"raw_array\":[1e-10]}") + .getBytes(StandardCharsets.UTF_8)); + + assertArrayEquals(new Double[] {1.5, 2.25}, (Double[]) row.getField(0)); + assertEquals( + "{\"pi\":3.141592653589793}", + row.getField(1), + "without DECIMAL a nested number keeps the double rendering"); + assertEquals( + "[1.0E-10]", + row.getField(2), + "without DECIMAL a nested small exponent keeps the double rendering"); + } + + @Test + public void testStringObjectAlongsideScalarDecimalKeepsNestedDigits() throws IOException { + // A scalar DECIMAL already enabled the document-wide decimal parser before this array fix, + // so this container rendering predates it and must stay identical. + SeaTunnelRowType rowType = + new SeaTunnelRowType( + new String[] {"amount", "raw"}, + new SeaTunnelDataType<?>[] {new DecimalType(38, 20), STRING_TYPE}); + JsonDeserializationSchema deserializationSchema = + new JsonDeserializationSchema(false, false, rowType); + + SeaTunnelRow row = + deserializationSchema.deserialize( + ("{\"amount\":" + + HIGH_PRECISION_DECIMAL_LITERAL + + ",\"raw\":{\"pi\":" + + HIGH_PRECISION_DECIMAL_LITERAL + + "}}") + .getBytes(StandardCharsets.UTF_8)); + + assertEquals( + 0, + new BigDecimal(HIGH_PRECISION_DECIMAL_LITERAL) + .compareTo((BigDecimal) row.getField(0)), + "the scalar DECIMAL keeps its exact value"); + assertEquals( + "{\"pi\":" + HIGH_PRECISION_DECIMAL_LITERAL + "}", + row.getField(1), + "a scalar DECIMAL renders the nested number exactly like an array DECIMAL does"); + } + @Test public void testArrayFieldRejectsNonArrayNodeInStrictMode() { JsonDeserializationSchema schema =
