You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by gi...@apache.org on 2026/09/01 07:17:17 UTC
(seatunnel) branch gh-readonly-queue/dev/pr-11937-6109b4600f1f86d8c851896dc9a44a4bd9c22e70 created (now 2a96f18bc5)
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a change to branch gh-readonly-queue/dev/pr-11937-6109b4600f1f86d8c851896dc9a44a4bd9c22e70
in repository https://gitbox.apache.org/repos/asf/seatunnel.git
at 2a96f18bc5 [Fix][Transform-V2] Handle TINYINT and SMALLINT in Zeta SQL numeric functions (#11937)
This branch includes the following new commits:
new 2a96f18bc5 [Fix][Transform-V2] Handle TINYINT and SMALLINT in Zeta SQL numeric functions (#11937)
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(seatunnel) 01/01: [Fix][Transform-V2] Handle TINYINT and SMALLINT in Zeta SQL numeric functions (#11937)
Posted by gi...@apache.org.
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-11937-6109b4600f1f86d8c851896dc9a44a4bd9c22e70
in repository https://gitbox.apache.org/repos/asf/seatunnel.git
commit 2a96f18bc5668cb6f2a538ddb5602fd816365161
Author: Sepuri Sai Krishna <sa...@gmail.com>
AuthorDate: Tue Sep 1 07:17:06 2026 +0000
[Fix][Transform-V2] Handle TINYINT and SMALLINT in Zeta SQL numeric functions (#11937)
---
.../introduction/concepts/incompatible-changes.md | 48 +++++
docs/en/transforms/sql-functions.md | 2 +
.../introduction/concepts/incompatible-changes.md | 40 ++++
docs/zh/transforms/sql-functions.md | 2 +
.../sql/zeta/functions/NumericFunction.java | 131 ++++++++++---
.../transform/sql/SQLNumericFunctionsTest.java | 71 +++++++
.../sql/zeta/functions/NumericFunctionTest.java | 211 +++++++++++++++++++++
7 files changed, 482 insertions(+), 23 deletions(-)
diff --git a/docs/en/introduction/concepts/incompatible-changes.md b/docs/en/introduction/concepts/incompatible-changes.md
index 6e2e76ae90..412d577756 100644
--- a/docs/en/introduction/concepts/incompatible-changes.md
+++ b/docs/en/introduction/concepts/incompatible-changes.md
@@ -225,6 +225,54 @@ You need to check this document before you upgrade to related version.
- Dividing by a zero `DECIMAL` now fails with a `TransformException` naming the operation, where the underlying cause was previously `java.lang.ArithmeticException("/ by zero")`. The failing expression was already reported either way, since the SQL engine wraps anything thrown while evaluating an expression; only the cause type changed. This matches how `MOD` by zero has always been reported.
**Migration Guide**: Results that were previously inflated by the old rounding mode, or truncated by the `double` conversion, will change. Multiplication results may now carry *fewer* decimal places than before: the old conversion sometimes emitted a value wider than the declared column scale, and that value is now rounded down to it, so a job reading `38.4375` from a `DECIMAL(38,2)` column will read `38.44` after upgrading. Any code that inspects the *cause* of a division failure and [...]
+- **[BREAKING]** SQL Transform `ABS`, and `ROUND` / `CEIL` / `CEILING` / `FLOOR` with a negative digit count, now
+ fail with a `TransformException` when the result does not fit the argument's own data type, instead of silently
+ wrapping around to a wrong — usually negative — value:
+
+ | Expression | Argument type | Previous result | Current result |
+ |------------|---------------|-----------------|----------------|
+ | `ABS(-2147483648)` | `INT` | `-2147483648` | `TransformException` |
+ | `ABS(-9223372036854775808)` | `BIGINT` | `-9223372036854775808` | `TransformException` |
+ | `ROUND(2147483647, -1)` | `INT` | `-2147483646` | `TransformException` |
+ | `ROUND(9223372036854775807, -1)` | `BIGINT` | `-9223372036854775806` | `TransformException` |
+ | `CEIL(32767, -1)` | `SMALLINT` | `-32766` | `TransformException` |
+ | `FLOOR(-2147483648, -1)` | `INT` | `2147483646` | `TransformException` |
+
+ `ABS` has always been documented this way — "ABS(-2147483648) should be 2147483648, but this value is not allowed
+ for this data type. It leads to an exception" — the implementation simply never did it. `TRUNC` / `TRUNCATE` round
+ toward zero and so can never grow a value out of its own range; they are unaffected, as are `FLOAT`, `DOUBLE` and
+ `DECIMAL` arguments.
+
+ **Migration Guide**: A job that previously emitted these wrapped values now fails on the row that overflows. Cast
+ the argument to a wider type to keep the job running — `ABS(CAST(int_col AS BIGINT))` or
+ `ROUND(CAST(int_col AS BIGINT), -1)` — or filter the offending rows out upstream. If a downstream system was
+ reconciled against the old wrapped values, re-baseline it after upgrading.
+
+- **[BREAKING]** SQL Transform now dispatches `TINYINT` and `SMALLINT` arguments correctly in the numeric
+ functions that previously omitted them. `ROUND` / `CEIL` / `CEILING` / `FLOOR` / `TRUNC` / `TRUNCATE` had no
+ `TINYINT` branch, so a `TINYINT` argument fell through the type switch and was returned unrounded, with no
+ exception and no log line. `ABS` and `SIGN` had no `TINYINT` or `SMALLINT` branch and rejected those columns
+ outright:
+
+ | Expression | Argument type | Previous result | Current result |
+ |------------|---------------|-----------------|----------------|
+ | `ROUND(44, -1)` | `TINYINT` | `44`, silently not rounded | `40` |
+ | `CEIL(44, -1)` | `TINYINT` | `44`, silently not rounded | `50` |
+ | `ROUND(127, -1)` | `TINYINT` | `127`, silently not rounded | `TransformException`, `130` exceeds `TINYINT` |
+ | `ABS(-44)` | `TINYINT` | `TransformException`, "Unsupported arg type" | `44` |
+ | `ABS(-300)` | `SMALLINT` | `TransformException`, "Unsupported arg type" | `300` |
+ | `SIGN(-44)` | `TINYINT` | `TransformException`, "Unsupported arg type" | `-1` |
+
+ The same type switch also gained a `default` branch, so any numeric type it does not handle now fails with a
+ `TransformException` instead of being returned unrounded. `SIGN` on a `DECIMAL` argument now uses
+ `BigDecimal.signum()` rather than a `double` conversion, so a value smaller than `Double.MIN_VALUE` reports its
+ true sign instead of `0`.
+
+ **Migration Guide**: A job with a `TINYINT` column that silently skipped rounding now receives the rounded value;
+ if a downstream system was reconciled against the old unrounded output, re-baseline it after upgrading. If a
+ rounded `TINYINT` no longer fits its own type, cast the argument to a wider type — `ROUND(CAST(tiny_col AS INT), -1)`
+ — or filter the offending rows out upstream. Queries that worked around the `ABS` / `SIGN` rejection by casting
+ (`ABS(CAST(tiny_col AS INT))`) continue to work unchanged and can be simplified at your convenience.
### Engine Behavior Changes
diff --git a/docs/en/transforms/sql-functions.md b/docs/en/transforms/sql-functions.md
index 28b8372067..6dea5deb3f 100644
--- a/docs/en/transforms/sql-functions.md
+++ b/docs/en/transforms/sql-functions.md
@@ -670,6 +670,8 @@ RAND()
Rounds to a number of fractional digits. This method returns value of the same type as argument, but with adjusted precision and scale, if applicable.
+Note that when `digitsInt` is negative and the argument is an integral type, the rounded value can fall outside the range of that type. For example, ROUND(2147483647, -1) should be 2147483650, but this value is not allowed for the INT data type. It leads to an exception. To avoid it cast argument of this function to a higher data type. CEIL and FLOOR overflow the same way; TRUNC rounds toward zero and therefore cannot.
+
Example:
ROUND(N, 2)
diff --git a/docs/zh/introduction/concepts/incompatible-changes.md b/docs/zh/introduction/concepts/incompatible-changes.md
index 8def490447..fc9e804ca1 100644
--- a/docs/zh/introduction/concepts/incompatible-changes.md
+++ b/docs/zh/introduction/concepts/incompatible-changes.md
@@ -206,6 +206,46 @@
- 除数为零的 `DECIMAL` 除法现在抛出标明该运算的 `TransformException`,而此前底层原因是 `java.lang.ArithmeticException("/ by zero")`。两种情况下出错的表达式本来就会被报告(SQL 引擎会包装表达式求值过程中抛出的任何异常),变化的只是 cause 的类型。这与 `MOD` 除零一直以来的报错方式保持一致。
**迁移指南**:之前被旧舍入模式抬高、或被 `double` 转换截断的结果都会发生变化。乘法结果的小数位数可能比以前*更少*:旧的转换有时会输出比列声明 scale 更宽的值,现在该值会被舍入到声明的 scale,因此原先从 `DECIMAL(38,2)` 列读到 `38.4375` 的作业,升级后会读到 `38.44`。如果下游系统已按旧值对账,升级后需要重新校准。任何为兼容旧行为而做的补偿(例如在除法后减去一个修正值)都应当移除。如果有代码检查除法失败的 cause 并匹配 `ArithmeticException`,需要改为 `TransformException`。
+- **[BREAKING]** SQL 转换的 `ABS`,以及使用负数位数的 `ROUND` / `CEIL` / `CEILING` / `FLOOR`,现在当结果无法用参数自身的数据类型表示时,
+ 会抛出 `TransformException`,而不再静默回绕成一个错误的(通常为负数的)值:
+
+ | 表达式 | 参数类型 | 之前的结果 | 当前的结果 |
+ |--------|----------|------------|------------|
+ | `ABS(-2147483648)` | `INT` | `-2147483648` | `TransformException` |
+ | `ABS(-9223372036854775808)` | `BIGINT` | `-9223372036854775808` | `TransformException` |
+ | `ROUND(2147483647, -1)` | `INT` | `-2147483646` | `TransformException` |
+ | `ROUND(9223372036854775807, -1)` | `BIGINT` | `-9223372036854775806` | `TransformException` |
+ | `CEIL(32767, -1)` | `SMALLINT` | `-32766` | `TransformException` |
+ | `FLOOR(-2147483648, -1)` | `INT` | `2147483646` | `TransformException` |
+
+ `ABS` 的文档一直是这样描述的——“ABS(-2147483648) 应该是 2147483648,但是这个值对于这个数据类型是不允许的。这会导致异常”——只是实现从未真正这么做。
+ `TRUNC` / `TRUNCATE` 向零舍入,绝不会把值撑出自身的取值范围,因此不受影响;`FLOAT`、`DOUBLE` 和 `DECIMAL` 参数同样不受影响。
+
+ **迁移指南**:之前会输出这些回绕值的作业,现在会在发生溢出的那一行失败。可以把参数转换为更宽的类型以保持作业运行——例如
+ `ABS(CAST(int_col AS BIGINT))` 或 `ROUND(CAST(int_col AS BIGINT), -1)`——或者在上游过滤掉这些行。如果下游系统已按旧的回绕值对账,
+ 升级后需要重新校准。
+
+- **[BREAKING]** SQL 转换现在能正确处理数值函数中此前被遗漏的 `TINYINT` 和 `SMALLINT` 参数。
+ `ROUND` / `CEIL` / `CEILING` / `FLOOR` / `TRUNC` / `TRUNCATE` 缺少 `TINYINT` 分支,因此 `TINYINT` 参数会直接穿过类型
+ switch 并被原样返回,既不舍入,也没有异常和日志。`ABS` 和 `SIGN` 缺少 `TINYINT` 与 `SMALLINT` 分支,会直接拒绝这些列:
+
+ | 表达式 | 参数类型 | 之前的结果 | 当前的结果 |
+ |--------|----------|------------|------------|
+ | `ROUND(44, -1)` | `TINYINT` | `44`,静默未舍入 | `40` |
+ | `CEIL(44, -1)` | `TINYINT` | `44`,静默未舍入 | `50` |
+ | `ROUND(127, -1)` | `TINYINT` | `127`,静默未舍入 | `TransformException`,`130` 超出 `TINYINT` |
+ | `ABS(-44)` | `TINYINT` | `TransformException`,“Unsupported arg type” | `44` |
+ | `ABS(-300)` | `SMALLINT` | `TransformException`,“Unsupported arg type” | `300` |
+ | `SIGN(-44)` | `TINYINT` | `TransformException`,“Unsupported arg type” | `-1` |
+
+ 该类型 switch 同时补上了 `default` 分支,因此任何未被处理的数值类型现在会抛出 `TransformException`,而不再被原样返回。
+ `SIGN` 处理 `DECIMAL` 参数时改用 `BigDecimal.signum()` 而非 `double` 转换,因此小于 `Double.MIN_VALUE` 的值会返回真实
+ 符号,而不是 `0`。
+
+ **迁移指南**:之前 `TINYINT` 列静默跳过舍入的作业,现在会得到真正舍入后的值;如果下游系统已按旧的未舍入结果对账,
+ 升级后需要重新校准。如果舍入后的 `TINYINT` 超出自身类型范围,可以把参数转换为更宽的类型——例如
+ `ROUND(CAST(tiny_col AS INT), -1)`——或者在上游过滤掉这些行。此前为绕开 `ABS` / `SIGN` 拒绝而使用的强制转换
+ (`ABS(CAST(tiny_col AS INT))`)仍然可以正常工作,可以在方便时再简化。
### 引擎行为变更
diff --git a/docs/zh/transforms/sql-functions.md b/docs/zh/transforms/sql-functions.md
index 9349ee1291..e2d9519c47 100644
--- a/docs/zh/transforms/sql-functions.md
+++ b/docs/zh/transforms/sql-functions.md
@@ -672,6 +672,8 @@ RAND()
四舍五入到指定的小数位数。该方法返回与参数相同类型的值,但如果适用,则调整精度和标度。
+请注意,当 `digitsInt` 为负数且参数为整数类型时,舍入后的值可能超出该类型的取值范围。例如,ROUND(2147483647, -1) 应该是 2147483650,但是这个值对于 INT 数据类型是不允许的。这会导致异常。为了避免这种情况,请将此函数的参数转换为更高的数据类型。CEIL 和 FLOOR 会以同样的方式溢出;TRUNC 向零舍入,因此不会溢出。
+
示例:
ROUND(N, 2)
diff --git a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunction.java b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunction.java
index 0a47fd069f..8cb7de272d 100644
--- a/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunction.java
+++ b/seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunction.java
@@ -24,6 +24,7 @@ import org.apache.seatunnel.transform.sql.zeta.ZetaSQLFunction;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
+import java.util.Locale;
import java.util.Random;
public class NumericFunction {
@@ -32,11 +33,33 @@ public class NumericFunction {
if (arg == null) {
return null;
}
+ if (arg instanceof Byte) {
+ byte value = arg.byteValue();
+ if (value == Byte.MIN_VALUE) {
+ throw absOverflow("TINYINT", value, Byte.MIN_VALUE, Byte.MAX_VALUE);
+ }
+ return (byte) Math.abs(value);
+ }
+ if (arg instanceof Short) {
+ short value = arg.shortValue();
+ if (value == Short.MIN_VALUE) {
+ throw absOverflow("SMALLINT", value, Short.MIN_VALUE, Short.MAX_VALUE);
+ }
+ return (short) Math.abs(value);
+ }
if (arg instanceof Integer) {
- return Math.abs(arg.intValue());
+ int value = arg.intValue();
+ if (value == Integer.MIN_VALUE) {
+ throw absOverflow("INT", value, Integer.MIN_VALUE, Integer.MAX_VALUE);
+ }
+ return Math.abs(value);
}
if (arg instanceof Long) {
- return Math.abs(arg.longValue());
+ long value = arg.longValue();
+ if (value == Long.MIN_VALUE) {
+ throw absOverflow("BIGINT", value, Long.MIN_VALUE, Long.MAX_VALUE);
+ }
+ return Math.abs(value);
}
if (arg instanceof Float) {
return Math.abs(arg.floatValue());
@@ -236,27 +259,30 @@ public class NumericFunction {
if (args.size() >= 2) {
v2 = (Number) args.get(1);
}
- return round(v1, v2, RoundingMode.CEILING);
+ return round(v1, v2, RoundingMode.CEILING, ZetaSQLFunction.CEIL);
}
- private static Number round(Number v1, Number v2, RoundingMode roundingMode) {
+ private static Number round(Number v1, Number v2, RoundingMode roundingMode, String function) {
int scale = v2 != null ? v2.intValue() : 0;
String t = v1.getClass().getSimpleName();
c:
- switch (t.toUpperCase()) {
+ // Locale.ROOT: under a Turkish default locale the lowercase 'i's in
+ // "BigDecimal" uppercase to '\u0130', so the label would miss its case and
+ // DECIMAL rounding would fall into the default branch below.
+ switch (t.toUpperCase(Locale.ROOT)) {
+ case "BYTE":
case "INTEGER":
case "SHORT":
case "LONG":
{
if (scale < 0) {
- long original = v1.longValue();
- long scaled =
- BigDecimal.valueOf(original)
- .setScale(scale, roundingMode)
- .longValue();
- if (original != scaled) {
- v1 = convertTo(t, scaled);
- }
+ // Round in BigDecimal and narrow only after checking the result fits.
+ // BigDecimal.longValue() keeps just the low-order 64 bits, and
+ // intValue()/shortValue() truncate the same way, so narrowing an
+ // out-of-range result used to turn a positive value negative.
+ BigDecimal rounded =
+ BigDecimal.valueOf(v1.longValue()).setScale(scale, roundingMode);
+ v1 = convertTo(t, rounded, function);
}
break;
}
@@ -295,23 +321,78 @@ public class NumericFunction {
v1 = t.equals("FLOAT") ? bd.floatValue() : bd.doubleValue();
break;
}
+ default:
+ // Without this, an unhandled numeric type fell through the switch and was
+ // returned unrounded, with no exception and no log line.
+ throw new TransformException(
+ CommonErrorCodeDeprecated.UNSUPPORTED_OPERATION,
+ String.format(
+ "Unsupported arg type %s of function %s",
+ v1.getClass().getName(), function));
}
return v1;
}
- private static Number convertTo(String valueType, Number column) {
- switch (valueType.toUpperCase()) {
+ /**
+ * Narrows an already-rounded integral value back to the argument's own type.
+ *
+ * @param valueType simple class name of the original argument
+ * @param value the rounded value, exact
+ * @param function SQL function name, used only for the error message
+ * @return the value in the original type
+ * @throws TransformException if the value does not fit that type
+ */
+ private static Number convertTo(String valueType, BigDecimal value, String function) {
+ switch (valueType.toUpperCase(Locale.ROOT)) {
+ case "BYTE":
+ return (byte)
+ checkIntegralRange(
+ value, Byte.MIN_VALUE, Byte.MAX_VALUE, "TINYINT", function);
case "INTEGER":
- return column.intValue();
+ return (int)
+ checkIntegralRange(
+ value, Integer.MIN_VALUE, Integer.MAX_VALUE, "INT", function);
case "SHORT":
- return column.shortValue();
+ return (short)
+ checkIntegralRange(
+ value, Short.MIN_VALUE, Short.MAX_VALUE, "SMALLINT", function);
case "LONG":
- return column.longValue();
+ return checkIntegralRange(
+ value, Long.MIN_VALUE, Long.MAX_VALUE, "BIGINT", function);
default:
throw new IllegalArgumentException();
}
}
+ /**
+ * Fails loudly when a rounded result cannot be represented in the argument's own type, rather
+ * than silently truncating it to a wrong (often negative) value.
+ */
+ private static long checkIntegralRange(
+ BigDecimal value, long min, long max, String sqlType, String function) {
+ if (value.compareTo(BigDecimal.valueOf(min)) < 0
+ || value.compareTo(BigDecimal.valueOf(max)) > 0) {
+ throw new TransformException(
+ CommonErrorCodeDeprecated.UNSUPPORTED_OPERATION,
+ String.format(
+ "Function %s produced %s, which is out of range for %s (%s to %s). "
+ + "Cast the argument to a wider data type to avoid this.",
+ function, value.toPlainString(), sqlType, min, max));
+ }
+ return value.longValue();
+ }
+
+ /** Mirrors the documented ABS contract: the minimum negative value has no absolute value. */
+ private static TransformException absOverflow(String sqlType, long value, long min, long max) {
+ return new TransformException(
+ CommonErrorCodeDeprecated.UNSUPPORTED_OPERATION,
+ String.format(
+ "Function %s cannot represent the absolute value of %s: %s allows %s to "
+ + "%s, so the result does not fit. Cast the argument to a wider "
+ + "data type to avoid this.",
+ ZetaSQLFunction.ABS, value, sqlType, min, max));
+ }
+
public static Double exp(List<Object> args) {
Number v1 = (Number) args.get(0);
if (v1 == null) {
@@ -335,7 +416,7 @@ public class NumericFunction {
if (args.size() >= 2) {
v2 = (Number) args.get(1);
}
- return round(v1, v2, RoundingMode.FLOOR);
+ return round(v1, v2, RoundingMode.FLOOR, ZetaSQLFunction.FLOOR);
}
public static Double ln(List<Object> args) {
@@ -444,7 +525,7 @@ public class NumericFunction {
if (args.size() >= 2) {
v2 = (Number) args.get(1);
}
- return round(v1, v2, RoundingMode.HALF_UP);
+ return round(v1, v2, RoundingMode.HALF_UP, ZetaSQLFunction.ROUND);
}
public static Integer sign(List<Object> args) {
@@ -452,6 +533,9 @@ public class NumericFunction {
if (v1 == null) {
return null;
}
+ if (v1 instanceof Byte || v1 instanceof Short) {
+ return Integer.signum(v1.intValue());
+ }
if (v1 instanceof Integer) {
return Integer.signum((Integer) v1);
}
@@ -467,8 +551,9 @@ public class NumericFunction {
return value == 0 || Float.isNaN(value) ? 0 : value < 0 ? -1 : 1;
}
if (v1 instanceof BigDecimal) {
- double value = v1.doubleValue();
- return value == 0 || Double.isNaN(value) ? 0 : value < 0 ? -1 : 1;
+ // signum() is exact: doubleValue() underflows to 0.0 for magnitudes below
+ // Double.MIN_VALUE, which reported a non-zero decimal as zero.
+ return ((BigDecimal) v1).signum();
}
throw new TransformException(
CommonErrorCodeDeprecated.UNSUPPORTED_OPERATION,
@@ -485,7 +570,7 @@ public class NumericFunction {
if (args.size() >= 2) {
v2 = (Number) args.get(1);
}
- return round(v1, v2, RoundingMode.DOWN);
+ return round(v1, v2, RoundingMode.DOWN, ZetaSQLFunction.TRUNC);
}
public static String trimScale(List<Object> args) {
diff --git a/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLNumericFunctionsTest.java b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLNumericFunctionsTest.java
index e4cd00e564..8e34814a61 100644
--- a/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLNumericFunctionsTest.java
+++ b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLNumericFunctionsTest.java
@@ -331,4 +331,75 @@ public class SQLNumericFunctionsTest {
Assertions.assertEquals(expectedV2, (Double) outRow.getField(1), 1e-9);
Assertions.assertEquals(expectedV3, (Double) outRow.getField(2), 1e-9);
}
+
+ @Test
+ public void testIntegralOverflowFailsInsteadOfProducingNegativeValues() {
+ SeaTunnelRowType rowType =
+ new SeaTunnelRowType(
+ new String[] {"i", "l"},
+ new SeaTunnelDataType[] {BasicType.INT_TYPE, BasicType.LONG_TYPE});
+
+ // ROUND(2147483647, -1) is 2147483650, which does not fit in an INT column. It used to
+ // wrap to -2147483646 and be written downstream as an ordinary row.
+ TransformException rounded =
+ Assertions.assertThrows(
+ TransformException.class,
+ () ->
+ runSql(
+ "select ROUND(i, -1) as r from dual",
+ rowType,
+ Integer.MAX_VALUE,
+ 0L));
+ // The SQL engine wraps anything thrown while evaluating an expression, so the range
+ // detail lives on the cause.
+ Assertions.assertTrue(rounded.getMessage().contains("ROUND(i, -1)"), rounded.getMessage());
+ Assertions.assertNotNull(rounded.getCause());
+ Assertions.assertTrue(
+ rounded.getCause().getMessage().contains("2147483650"),
+ rounded.getCause().getMessage());
+
+ // ABS of the minimum BIGINT has no representation, so the row used to keep its sign.
+ TransformException absolute =
+ Assertions.assertThrows(
+ TransformException.class,
+ () -> runSql("select ABS(l) as a from dual", rowType, 0, Long.MIN_VALUE));
+ Assertions.assertNotNull(absolute.getCause());
+ Assertions.assertTrue(
+ absolute.getCause().getMessage().contains("BIGINT"),
+ absolute.getCause().getMessage());
+
+ SeaTunnelRow outRow =
+ runSql("select ROUND(i, -1) as r, ABS(l) as a from dual", rowType, 1234, -5L);
+ Assertions.assertEquals(1230, outRow.getField(0));
+ Assertions.assertEquals(5L, outRow.getField(1));
+ }
+
+ @Test
+ public void testTinyIntAndSmallIntFlowThroughNumericFunctions() {
+ SeaTunnelRowType rowType =
+ new SeaTunnelRowType(
+ new String[] {"tiny_v", "small_v"},
+ new SeaTunnelDataType[] {BasicType.BYTE_TYPE, BasicType.SHORT_TYPE});
+
+ // ROUND on a TINYINT column used to fall through the type switch and return the input
+ // unchanged, while the identical expression one type up rounded correctly.
+ SeaTunnelRow rounded =
+ runSql(
+ "select ROUND(tiny_v, -1) as r_tiny, ROUND(small_v, -2) as r_small from dual",
+ rowType,
+ (byte) 44,
+ (short) 1234);
+ Assertions.assertEquals((byte) 40, rounded.getField(0));
+ Assertions.assertEquals((short) 1200, rounded.getField(1));
+
+ // ABS and SIGN used to reject both column types outright.
+ SeaTunnelRow signed =
+ runSql(
+ "select ABS(tiny_v) as a, SIGN(small_v) as s from dual",
+ rowType,
+ (byte) -44,
+ (short) -1234);
+ Assertions.assertEquals((byte) 44, signed.getField(0));
+ Assertions.assertEquals(-1, signed.getField(1));
+ }
}
diff --git a/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunctionTest.java b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunctionTest.java
index d8dee6b331..3f4c835e4e 100644
--- a/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunctionTest.java
+++ b/seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/zeta/functions/NumericFunctionTest.java
@@ -22,6 +22,7 @@ import org.apache.seatunnel.api.table.type.DecimalType;
import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;
import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+import org.apache.seatunnel.transform.exception.TransformException;
import org.apache.seatunnel.transform.sql.SQLEngine;
import org.apache.seatunnel.transform.sql.SQLEngineFactory;
@@ -32,6 +33,7 @@ import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.Locale;
public class NumericFunctionTest {
@@ -276,4 +278,213 @@ public class NumericFunctionTest {
NumericFunction.sign(Collections.singletonList(new BigDecimal("0.0000")))
.intValue());
}
+
+ @Test
+ public void testAbsRejectsMinValueInsteadOfReturningItUnchanged() {
+ // Math.abs(MIN_VALUE) == MIN_VALUE, so ABS used to hand back a negative "absolute value".
+ TransformException intError =
+ Assertions.assertThrows(
+ TransformException.class,
+ () -> NumericFunction.abs(Collections.singletonList(Integer.MIN_VALUE)));
+ Assertions.assertTrue(intError.getMessage().contains("INT"), intError.getMessage());
+ Assertions.assertTrue(intError.getMessage().contains("-2147483648"), intError.getMessage());
+
+ TransformException longError =
+ Assertions.assertThrows(
+ TransformException.class,
+ () -> NumericFunction.abs(Collections.singletonList(Long.MIN_VALUE)));
+ Assertions.assertTrue(longError.getMessage().contains("BIGINT"), longError.getMessage());
+
+ // Everything one step inside the boundary is representable and must still work.
+ Assertions.assertEquals(
+ Integer.MAX_VALUE,
+ NumericFunction.abs(Collections.singletonList(Integer.MIN_VALUE + 1)));
+ Assertions.assertEquals(
+ Long.MAX_VALUE, NumericFunction.abs(Collections.singletonList(Long.MIN_VALUE + 1)));
+ }
+
+ @Test
+ public void testNegativeScaleRoundingRejectsResultsThatDoNotFit() {
+ // ROUND(2147483647, -1) is 2147483650. Narrowing that through intValue() used to wrap it
+ // to -2147483646, turning the largest INT into a negative number.
+ TransformException roundInt =
+ Assertions.assertThrows(
+ TransformException.class,
+ () -> NumericFunction.round(Arrays.asList(Integer.MAX_VALUE, -1)));
+ Assertions.assertTrue(roundInt.getMessage().contains("ROUND"), roundInt.getMessage());
+ Assertions.assertTrue(roundInt.getMessage().contains("INT"), roundInt.getMessage());
+ Assertions.assertTrue(roundInt.getMessage().contains("2147483650"), roundInt.getMessage());
+
+ // CEIL overflows at the top of the range, FLOOR at the bottom.
+ TransformException ceilInt =
+ Assertions.assertThrows(
+ TransformException.class,
+ () -> NumericFunction.ceil(Arrays.asList(Integer.MAX_VALUE, -1)));
+ Assertions.assertTrue(ceilInt.getMessage().contains("CEIL"), ceilInt.getMessage());
+
+ TransformException floorInt =
+ Assertions.assertThrows(
+ TransformException.class,
+ () -> NumericFunction.floor(Arrays.asList(Integer.MIN_VALUE, -1)));
+ Assertions.assertTrue(floorInt.getMessage().contains("FLOOR"), floorInt.getMessage());
+
+ // BIGINT overflows in BigDecimal.longValue() itself, before any narrowing cast.
+ TransformException roundLong =
+ Assertions.assertThrows(
+ TransformException.class,
+ () -> NumericFunction.round(Arrays.asList(Long.MAX_VALUE, -1)));
+ Assertions.assertTrue(roundLong.getMessage().contains("BIGINT"), roundLong.getMessage());
+
+ // SMALLINT is narrowed by shortValue(), which wraps the same way.
+ TransformException roundShort =
+ Assertions.assertThrows(
+ TransformException.class,
+ () -> NumericFunction.round(Arrays.asList(Short.MAX_VALUE, -1)));
+ Assertions.assertTrue(
+ roundShort.getMessage().contains("SMALLINT"), roundShort.getMessage());
+
+ // TRUNC rounds toward zero, so it can never grow a value out of its own range.
+ Assertions.assertEquals(
+ 2147483640, NumericFunction.trunc(Arrays.asList(Integer.MAX_VALUE, -1)));
+ }
+
+ @Test
+ public void testNegativeScaleRoundingKeepsArgumentTypeWhenResultFits() {
+ Number roundedInt = NumericFunction.round(Arrays.asList(1234, -2));
+ Assertions.assertEquals(Integer.valueOf(1200), roundedInt);
+
+ Number roundedShort = NumericFunction.round(Arrays.asList(Short.valueOf((short) 1234), -2));
+ Assertions.assertEquals(Short.valueOf((short) 1200), roundedShort);
+
+ Number roundedLong = NumericFunction.round(Arrays.asList(1234L, -2));
+ Assertions.assertEquals(Long.valueOf(1200L), roundedLong);
+
+ // Rounding away every significant digit yields zero rather than an out-of-range error.
+ Assertions.assertEquals(Integer.valueOf(0), NumericFunction.round(Arrays.asList(1234, -9)));
+ }
+
+ @Test
+ public void testRoundingFamilyHandlesTinyInt() {
+ // round()'s switch had no BYTE case, so a TINYINT argument fell straight through and
+ // was returned unrounded - no exception, no log line.
+ Assertions.assertEquals(
+ Byte.valueOf((byte) 40), NumericFunction.round(Arrays.asList((byte) 44, -1)));
+ Assertions.assertEquals(
+ Byte.valueOf((byte) 50), NumericFunction.ceil(Arrays.asList((byte) 44, -1)));
+ Assertions.assertEquals(
+ Byte.valueOf((byte) 40), NumericFunction.floor(Arrays.asList((byte) 44, -1)));
+ Assertions.assertEquals(
+ Byte.valueOf((byte) 40), NumericFunction.trunc(Arrays.asList((byte) 44, -1)));
+
+ // Scale 0 leaves an integral argument alone, as it does for the other integral types.
+ Assertions.assertEquals(
+ Byte.valueOf((byte) 44), NumericFunction.round(Arrays.asList((byte) 44)));
+
+ // Rounding away every significant digit yields zero rather than an out-of-range error.
+ Assertions.assertEquals(
+ Byte.valueOf((byte) 0), NumericFunction.round(Arrays.asList((byte) 44, -9)));
+ }
+
+ @Test
+ public void testTinyIntRoundingRejectsResultsThatDoNotFit() {
+ // ROUND(127, -1) is 130, which does not fit a TINYINT.
+ TransformException error =
+ Assertions.assertThrows(
+ TransformException.class,
+ () -> NumericFunction.round(Arrays.asList(Byte.MAX_VALUE, -1)));
+ Assertions.assertTrue(error.getMessage().contains("TINYINT"), error.getMessage());
+ Assertions.assertTrue(error.getMessage().contains("130"), error.getMessage());
+
+ // TRUNC moves toward zero, so it can never grow a value out of its own range.
+ Assertions.assertEquals(
+ Byte.valueOf((byte) 120), NumericFunction.trunc(Arrays.asList(Byte.MAX_VALUE, -1)));
+ }
+
+ @Test
+ public void testRoundingRejectsUnhandledNumericTypes() {
+ // The switch had no default, so an unhandled Number was returned unrounded instead of
+ // failing. BigInteger is the same type the ABS test uses for this purpose.
+ TransformException error =
+ Assertions.assertThrows(
+ TransformException.class,
+ () ->
+ NumericFunction.round(
+ Arrays.asList(new java.math.BigInteger("12"), -1)));
+ Assertions.assertTrue(error.getMessage().contains("ROUND"), error.getMessage());
+ Assertions.assertTrue(
+ error.getMessage().contains("java.math.BigInteger"), error.getMessage());
+ }
+
+ @Test
+ public void testRoundingDispatchIsLocaleIndependent() {
+ // "BigDecimal".toUpperCase() is "B\u0130GDEC\u0130MAL" under a Turkish default locale,
+ // which no longer matches the "BIGDECIMAL" case label. That used to fall through the
+ // switch and return the value unrounded; once the switch grew a default it would throw
+ // instead. Asserting the rounded result rules out both failure modes at once.
+ Locale previous = Locale.getDefault();
+ try {
+ Locale.setDefault(new Locale("tr", "TR"));
+ Assertions.assertEquals(
+ new BigDecimal("1.3"),
+ NumericFunction.round(Arrays.asList(new BigDecimal("1.25"), 1)));
+ Assertions.assertEquals(
+ new BigDecimal("2"),
+ NumericFunction.ceil(Collections.singletonList(new BigDecimal("1.25"))));
+ } finally {
+ Locale.setDefault(previous);
+ }
+ }
+
+ @Test
+ public void testAbsAndSignAcceptTinyIntAndSmallInt() {
+ // Both used to throw "Unsupported arg type" on these two documented types.
+ Assertions.assertEquals(
+ Byte.valueOf((byte) 10),
+ NumericFunction.abs(Collections.singletonList((byte) -10)));
+ Assertions.assertEquals(
+ Short.valueOf((short) 300),
+ NumericFunction.abs(Collections.singletonList((short) -300)));
+
+ Assertions.assertEquals(-1, NumericFunction.sign(Collections.singletonList((byte) -10)));
+ Assertions.assertEquals(1, NumericFunction.sign(Collections.singletonList((short) 300)));
+ Assertions.assertEquals(0, NumericFunction.sign(Collections.singletonList((byte) 0)));
+ }
+
+ @Test
+ public void testAbsRejectsTinyIntAndSmallIntMinValue() {
+ // Math.abs promotes to int, so (byte) -128 would come back as 128 and no longer fit.
+ TransformException tinyError =
+ Assertions.assertThrows(
+ TransformException.class,
+ () -> NumericFunction.abs(Collections.singletonList(Byte.MIN_VALUE)));
+ Assertions.assertTrue(tinyError.getMessage().contains("TINYINT"), tinyError.getMessage());
+ Assertions.assertTrue(tinyError.getMessage().contains("-128"), tinyError.getMessage());
+
+ TransformException smallError =
+ Assertions.assertThrows(
+ TransformException.class,
+ () -> NumericFunction.abs(Collections.singletonList(Short.MIN_VALUE)));
+ Assertions.assertTrue(
+ smallError.getMessage().contains("SMALLINT"), smallError.getMessage());
+
+ // Everything one step inside the boundary is representable and must still work.
+ Assertions.assertEquals(
+ Byte.valueOf(Byte.MAX_VALUE),
+ NumericFunction.abs(Collections.singletonList((byte) (Byte.MIN_VALUE + 1))));
+ Assertions.assertEquals(
+ Short.valueOf(Short.MAX_VALUE),
+ NumericFunction.abs(Collections.singletonList((short) (Short.MIN_VALUE + 1))));
+ }
+
+ @Test
+ public void testSignIsExactForDecimalsBelowDoubleRange() {
+ // doubleValue() underflows to 0.0 below Double.MIN_VALUE, so a non-zero decimal used to
+ // report as zero. signum() is exact.
+ Assertions.assertEquals(
+ 1, NumericFunction.sign(Collections.singletonList(new BigDecimal("1E-400"))));
+ Assertions.assertEquals(
+ -1, NumericFunction.sign(Collections.singletonList(new BigDecimal("-1E-400"))));
+ Assertions.assertEquals(
+ 0, NumericFunction.sign(Collections.singletonList(new BigDecimal("0.0000"))));
+ }
}