Skip to content

Commit

Permalink
Fix inferring type of decimals with leading zeros in MongoDB
Browse files Browse the repository at this point in the history
  • Loading branch information
nineinchnick authored and hashhar committed Sep 20, 2023
1 parent 005e84b commit 917be6e
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -922,7 +922,10 @@ else if (value instanceof Decimal128 decimal128) {
catch (ArithmeticException e) {
return Optional.empty();
}
typeSignature = createDecimalType(decimal.precision(), decimal.scale()).getTypeSignature();
// Java's BigDecimal.precision() returns precision for the unscaled value, so it skips leading zeros for values lower than 1.
// Trino's (SQL) decimal precision must include leading zeros in values less than 1, and can never be lower than scale.
int precision = Math.max(decimal.precision(), decimal.scale());
typeSignature = createDecimalType(precision, decimal.scale()).getTypeSignature();
}
else if (value instanceof Date) {
typeSignature = TIMESTAMP_MILLIS.getTypeSignature();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,8 @@ public void testDecimal()
.addRoundTrip("NumberDecimal(\"2\")", "CAST('2' AS decimal(1, 0))")
.addRoundTrip("NumberDecimal(\"2.3\")", "CAST('2.3' AS decimal(2, 1))")
.addRoundTrip("NumberDecimal(\"-2.3\")", "CAST('-2.3' AS decimal(2, 1))")
.addRoundTrip("NumberDecimal(\"0.03\")", "CAST('0.03' AS decimal(2, 2))")
.addRoundTrip("NumberDecimal(\"-0.03\")", "CAST('-0.03' AS decimal(2, 2))")
.addRoundTrip("NumberDecimal(\"1234567890123456789012345678901234\")", "CAST('1234567890123456789012345678901234' AS decimal(34, 0))") // 34 is the max precision in Decimal128
.addRoundTrip("NumberDecimal(\"1234567890123456.789012345678901234\")", "CAST('1234567890123456.789012345678901234' AS decimal(34, 18))")
.execute(getQueryRunner(), mongoCreateAndInsert(getSession(), "tpch", "test_decimal"));
Expand Down

0 comments on commit 917be6e

Please sign in to comment.