vlsi commented on code in PR #5297:
URL: https://github.com/apache/calcite/pull/5297#discussion_r4348622173


##########
site/_docs/reference.md:
##########
@@ -1828,6 +1828,28 @@ i: implicit cast / e: explicit cast / x: not allowed
   make `1 = true` and `0 = false` always evaluate to `TRUE`;
   if there is numeric type operand, find common type for both operands;
   if operands are `UUID` and `CHARACTER` or `BINARY`, promote to `UUID`.
+  By default, comparing `DECIMAL` with `REAL` or `DOUBLE` narrows to the
+  approximate type (`REAL` has 24-bit mantissa, about 7 decimal digits),
+  so distinct values can compare as equal. The same applies to `BETWEEN`,
+  `IN`, quantified comparisons, `NATURAL JOIN`, and `JOIN USING`, and to
+  the element types of `ARRAY`, `MAP`, and `ROW`. (`CASE`, `COALESCE`,
+  and set operations are not affected: they already use `DOUBLE` for this

Review Comment:
   The override does not change `DECIMAL` compared with `DOUBLE`: `super` 
already returns `DOUBLE` for that pair. As written, a reader with wrong 
`DECIMAL`/`DOUBLE` results finds a recipe that changes nothing for them, and 
learns why only from the caveat at the end of the paragraph. Also, only the 
`DECIMAL` operand is cast, so "narrows to the approximate type" describes the 
operand, not the comparison.
   
   The lists of statements are incomplete too (the `reference.md` half of my 
earlier nit). `IS [NOT] DISTINCT FROM` and `NULLIF` compare as `REAL` by 
default: `NULLIF(d.k, f.k)` is planned as `CASE(=(CAST($0):REAL NOT NULL, $1), 
...)`, so a reader who sees `CASE` listed as unaffected will assume `NULLIF` is 
unaffected too. Multi-row `VALUES` already gives `DOUBLE` for this pair, like 
`CASE` and `COALESCE`. Suggested:
   
   ```suggestion
     By default, comparing `DECIMAL` with `REAL` converts the `DECIMAL`
     operand to `REAL`, which has a 24-bit mantissa (about 7 decimal digits),
     so distinct values can compare as equal. The same applies to `BETWEEN`,
     `IN`, `IS [NOT] DISTINCT FROM`, `NULLIF`, quantified comparisons,
     `NATURAL JOIN`, and `JOIN USING`, and to the element types of `ARRAY`,
     `MAP`, and `ROW`. (`CASE`, `COALESCE`, multi-row `VALUES`, and set
     operations are not affected: they already use `DOUBLE` for this
   ```



##########
site/_docs/reference.md:
##########
@@ -1828,6 +1828,28 @@ i: implicit cast / e: explicit cast / x: not allowed
   make `1 = true` and `0 = false` always evaluate to `TRUE`;
   if there is numeric type operand, find common type for both operands;
   if operands are `UUID` and `CHARACTER` or `BINARY`, promote to `UUID`.
+  By default, comparing `DECIMAL` with `REAL` or `DOUBLE` narrows to the
+  approximate type (`REAL` has 24-bit mantissa, about 7 decimal digits),
+  so distinct values can compare as equal. The same applies to `BETWEEN`,
+  `IN`, quantified comparisons, `NATURAL JOIN`, and `JOIN USING`, and to
+  the element types of `ARRAY`, `MAP`, and `ROW`. (`CASE`, `COALESCE`,
+  and set operations are not affected: they already use `DOUBLE` for this
+  combination.) Integer types have the same defect: `INTEGER` (31 bits)
+  and `BIGINT` (63 bits) compared with `REAL` lose precision the same
+  way, and `BIGINT` compared with `DOUBLE` does too; the override below
+  leaves those alone.
+  To widen to `DOUBLE` instead, override
+  `TypeCoercion#commonTypeForBinaryComparison` in a `TypeCoercionImpl`
+  subclass and install it via
+  `SqlValidator.Config#withTypeCoercionFactory`. The rule is: call
+  `super`, and replace the result with `DOUBLE` only when `super` returns
+  an approximate type and one operand is `DECIMAL`; this leaves
+  `DECIMAL` vs `VARCHAR`, `DECIMAL` vs `INTEGER`, and non-`DECIMAL` pairs
+  unchanged. This opt-in is available to applications using `Frameworks`
+  or `SqlValidatorUtil`; there is no JDBC connection property for it.
+  `DOUBLE` has a 53-bit mantissa, about 15 decimal digits, so `DECIMAL`
+  values with more significant digits can still compare as equal after
+  widening.

Review Comment:
   Widening also changes the result of comparisons with exact literals, and 
neither this paragraph nor the `WideningTypeCoercion` javadoc says so. A 
literal such as `0.1` has type `DECIMAL(2, 1)`, so with the override `real_col 
= 0.1` compares `CAST(real_col AS DOUBLE)` with `0.1`. `CAST(0.1 AS REAL)` is 
0.100000001490116… in `DOUBLE`, so `SELECT * FROM (VALUES (CAST(0.1 AS REAL))) 
AS t(r) WHERE r = 0.1` returns 1 row by default and 0 rows with the override. 
The same goes for `IN (0.1, ...)` and for `BETWEEN` with such a literal as its 
upper bound (`r BETWEEN 0 AND 0.1`). A user who stores `REAL` values and 
filters them with literals loses rows after opting in. Suggested:
   
   ```suggestion
     `DOUBLE` has a 53-bit mantissa, about 15 decimal digits, so `DECIMAL`
     values with more significant digits can still compare as equal after
     widening. Widening also changes comparisons of a `REAL` column with an
     exact literal: `0.1` has type `DECIMAL(2, 1)`, so `real_col = 0.1` is
     false for a `REAL` value stored as `0.1`, which converts to
     0.100000001490116… in `DOUBLE`.
   ```



##########
core/src/test/java/org/apache/calcite/test/TypeCoercionTest.java:
##########
@@ -484,6 +486,75 @@ private static ImmutableList<RelDataType> combine(
         f.recordType("a", f.arrayType(f.nullableIntType)));
   }
 
+  /**
+   * Test case for
+   * <a 
href="https://issues.apache.org/jira/browse/CALCITE-7827";>[CALCITE-7827]
+   * Document precision loss in DECIMAL/REAL comparisons and how to widen them 
to DOUBLE</a>.
+   *
+   * <p>A custom {@link TypeCoercion} that overrides
+   * {@link TypeCoercion#commonTypeForBinaryComparison} can widen to DOUBLE,
+   * including for the element types of ARRAY and MAP and the fields of ROW. */
+  @Test void testComparisonCoercionDecimalWithApproximateNumericOverride() {
+    final Fixture f = fixture();
+    final RelDataType decimal54 = f.decimalType(5, 4);
+    final RelDataType nullableDecimal54 =
+        f.typeFactory.createTypeWithNullability(decimal54, true);
+
+    final RelDataType decimal144 =
+        f.typeFactory.createSqlType(SqlTypeName.DECIMAL, 14, 4);
+
+    final SqlValidator validator = SqlTestFactory.INSTANCE.createValidator();
+    final Fixture w =
+        new Fixture(f.typeFactory,
+            new WideningTypeCoercion(f.typeFactory, validator));
+    w.comparisonCommonType(decimal54, f.realType, f.doubleType);
+    w.comparisonCommonType(nullableDecimal54, f.realType, 
f.nullableDoubleType);
+    w.comparisonCommonType(decimal54, f.nullableRealType, 
f.nullableDoubleType);
+    // DECIMAL operand but exact common type: unchanged.
+    w.comparisonCommonType(decimal54, f.intType, decimal144);
+    // No DECIMAL operand: unchanged.
+    w.comparisonCommonType(f.intType, f.realType, f.realType);
+    w.comparisonCommonType(f.realType, f.doubleType, f.doubleType);
+    // Nested types.
+    w.comparisonCommonType(f.arrayType(decimal54), f.arrayType(f.realType),
+        f.arrayType(f.doubleType));
+    w.comparisonCommonType(f.mapType(f.intType, decimal54),

Review Comment:
   The javadoc on line 496 says the override covers "the element types of ARRAY 
and MAP", and the `AbstractTypeCoercion` javadoc says the method recurses into 
"both key and value types" of a MAP, but this row puts DECIMAL and REAL only in 
the value. Please add a row with them in the key: 
`w.comparisonCommonType(f.mapType(decimal54, f.intType), f.mapType(f.realType, 
f.intType), f.mapType(f.doubleType, f.intType))`.



##########
core/src/test/java/org/apache/calcite/test/TypeCoercionTest.java:
##########
@@ -484,6 +486,75 @@ private static ImmutableList<RelDataType> combine(
         f.recordType("a", f.arrayType(f.nullableIntType)));
   }
 
+  /**
+   * Test case for
+   * <a 
href="https://issues.apache.org/jira/browse/CALCITE-7827";>[CALCITE-7827]
+   * Document precision loss in DECIMAL/REAL comparisons and how to widen them 
to DOUBLE</a>.
+   *
+   * <p>A custom {@link TypeCoercion} that overrides
+   * {@link TypeCoercion#commonTypeForBinaryComparison} can widen to DOUBLE,
+   * including for the element types of ARRAY and MAP and the fields of ROW. */
+  @Test void testComparisonCoercionDecimalWithApproximateNumericOverride() {
+    final Fixture f = fixture();
+    final RelDataType decimal54 = f.decimalType(5, 4);
+    final RelDataType nullableDecimal54 =
+        f.typeFactory.createTypeWithNullability(decimal54, true);
+
+    final RelDataType decimal144 =
+        f.typeFactory.createSqlType(SqlTypeName.DECIMAL, 14, 4);
+
+    final SqlValidator validator = SqlTestFactory.INSTANCE.createValidator();
+    final Fixture w =
+        new Fixture(f.typeFactory,
+            new WideningTypeCoercion(f.typeFactory, validator));
+    w.comparisonCommonType(decimal54, f.realType, f.doubleType);
+    w.comparisonCommonType(nullableDecimal54, f.realType, 
f.nullableDoubleType);
+    w.comparisonCommonType(decimal54, f.nullableRealType, 
f.nullableDoubleType);
+    // DECIMAL operand but exact common type: unchanged.
+    w.comparisonCommonType(decimal54, f.intType, decimal144);
+    // No DECIMAL operand: unchanged.
+    w.comparisonCommonType(f.intType, f.realType, f.realType);
+    w.comparisonCommonType(f.realType, f.doubleType, f.doubleType);

Review Comment:
   `w.comparisonCommonType(f.realType, f.doubleType, f.doubleType)` passes with 
or without the override, and with an override that drops either condition: 
`super` already returns `DOUBLE` for this pair. Line 516 catches an override 
that drops the DECIMAL check, and line 514 one that drops the approximate 
check. Please drop this row.



##########
core/src/test/java/org/apache/calcite/test/JdbcTest.java:
##########
@@ -1836,6 +1840,69 @@ private void checkResultSetMetaData(Connection 
connection, String sql)
         .returns("C0=5.5; C1=5; C2=1.4; C3=1; C4=0; C5=0\n");
   }
 
+  /** Installs {@link TypeCoercionTest.WideningTypeCoercion} via
+   * {@link Hook#STRING_TO_QUERY} for use in boundary tests for
+   * <a 
href="https://issues.apache.org/jira/browse/CALCITE-7827";>[CALCITE-7827]</a>. */
+  private static Consumer<Pair<FrameworkConfig, Holder<CalcitePrepare.Query>>>
+      wideningHook() {
+    return pair -> {
+      final String sql = requireNonNull(pair.right.get().sql);
+      final FrameworkConfig config =
+          Frameworks.newConfigBuilder(pair.left)
+              .sqlValidatorConfig(pair.left.getSqlValidatorConfig()
+                  
.withTypeCoercionFactory(TypeCoercionTest.WideningTypeCoercion::new))
+              .build();
+      final Planner planner = Frameworks.getPlanner(config);
+      try {
+        final RelRoot root = planner.rel(planner.validate(planner.parse(sql)));
+        pair.right.set(CalcitePrepare.Query.of(root.project()));
+      } catch (Exception e) {
+        throw TestUtil.rethrow(e);
+      }
+    };
+  }
+
+  /** Test case for
+   * <a 
href="https://issues.apache.org/jira/browse/CALCITE-7827";>[CALCITE-7827]
+   * Document precision loss in DECIMAL/REAL comparisons and how to widen them 
to DOUBLE</a>.
+   *
+   * <p>Default behavior: DECIMAL(18, 3) compared with REAL narrows to REAL
+   * (24-bit mantissa, about 7 decimal digits). {@code CAST(140737488355328 AS
+   * REAL)} is exactly 2^47. REAL's ULP at 2^47 is 2^(47-23) = 2^24 ≈ 16.7
+   * million, so the .016 fractional part is completely lost; both values
+   * narrow to 2^47 in REAL and the join incorrectly returns 1 row.
+   * Compare {@link 
#testDecimalRealComparisonWidenedToDoubleDistinguishesValues}, which
+   * runs the same SQL with {@link TypeCoercionTest.WideningTypeCoercion}
+   * and returns 0 rows. */
+  @Test void testDecimalRealComparisonDefaultNarrowsToReal() {
+    CalciteAssert.that()
+        .query("SELECT *\n"
+            + "FROM (VALUES (CAST(140737488355328.016 AS DECIMAL(18, 3)))) AS 
d(k)\n"
+            + "JOIN (VALUES (CAST(140737488355328 AS REAL))) AS f(k) ON d.k = 
f.k")
+        .returnsCount(1);
+  }
+
+  /** Test case for
+   * <a 
href="https://issues.apache.org/jira/browse/CALCITE-7827";>[CALCITE-7827]
+   * Document precision loss in DECIMAL/REAL comparisons and how to widen them 
to DOUBLE</a>.
+   *
+   * <p>With {@link TypeCoercionTest.WideningTypeCoercion}, DECIMAL(18, 3)
+   * compared with REAL widens to DOUBLE. {@code CAST(140737488355328 AS REAL)}
+   * is exactly 2^47 (a power of two, exactly representable as REAL). DOUBLE
+   * has 53-bit mantissa; the unit in the last place (ULP) at 2^47 is
+   * 2^(47-52) = 0.03125. The DECIMAL value 140737488355328.016 exceeds the
+   * half-ULP (0.015625), so it rounds to the next DOUBLE above 2^47. The

Review Comment:
   The value 140737488355328.016 does not exceed 0.015625; its distance from 
2^47 does. Suggested:
   
   ```suggestion
      * has a 53-bit mantissa; the unit in the last place (ULP) at 2^47 is
      * 2^(47-52) = 0.03125. The fractional part .016 exceeds half a ULP
      * (0.015625), so the DECIMAL value rounds to the next DOUBLE above 2^47. 
The
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to