spark-test commented on code in PR #60455:
URL: https://github.com/apache/spark/pull/60455#discussion_r4569837926
##########
sql/core/src/main/scala/org/apache/spark/sql/jdbc/JdbcDialects.scala:
##########
@@ -544,6 +560,17 @@ abstract class JdbcDialect extends Serializable with
Logging {
}
}
+ /**
+ * Truncates `expr` toward zero, so that a cast from a fractional type to an
integral type that
+ * is pushed down matches Spark, which truncates rather than rounds.
Dialects for databases that
+ * round such casts override this with the database's truncating function.
The default returns
+ * `expr` unchanged, for databases whose cast already truncates like Spark.
+ * @param expr The SQL string of the value being cast.
+ * @return The SQL string to cast instead of `expr`.
+ */
+ @Since("4.4.0")
+ def truncateFractionalValue(expr: String): String = expr
Review Comment:
**Non-blocking (P2):** If a user registers a custom dialect for a URL that a
built-in dialect also handles, for example with `JdbcDialects.registerDialect`
for `jdbc:postgresql`, `JdbcDialects.get` returns an `AggregatedDialect` of
both. `AggregatedDialect` forwards `getJDBCType` and `timestampNTZAsWallClock`
to its members but not this new hook, so its builder calls this identity
default. A pushed `CAST(d AS INT) = 2` then goes to Postgres as `CAST("d" AS
INTEGER) = 2`, which Postgres evaluates by rounding, so d = 2.6 is not matched,
while `PostgresDialect` on its own now sends `CAST(TRUNC("d") AS INTEGER) = 2`.
Pushed filters, aggregates and sort keys on Postgres, Oracle, Snowflake and H2
keep the rounded result in that setup, and a member dialect's own override of
the hook is ignored. Forwarding the hook in `AggregatedDialect` as the first
member result that differs from its input, following its rule that the first
non-neutral answer wins, would close the gap.
**Verification:**
- **Regression:** Compiled-SQL coverage wraps a custom dialect and a
rounding built-in dialect such as Postgres or Oracle in an AggregatedDialect,
in both member orders, and shows the pushed fractional-to-integral cast wrapped
in the member's truncating function, while members that all keep the default
give the plain cast.
##########
sql/core/src/main/scala/org/apache/spark/sql/jdbc/JdbcDialects.scala:
##########
@@ -460,8 +460,24 @@ abstract class JdbcDialect extends Serializable with
Logging {
override def visitCast(expr: String, exprDataType: DataType, dataType:
DataType): String = {
val databaseTypeDefinition =
-
getJDBCType(dataType).map(_.databaseTypeDefinition).getOrElse(dataType.typeName)
- s"CAST($expr AS $databaseTypeDefinition)"
+ getJDBCType(dataType).map(_.databaseTypeDefinition).getOrElse(dataType
match {
+ // Spark's type names `short` and `long` are not valid SQL types in
most databases.
+ case ShortType => "SMALLINT"
+ case IntegerType => "INTEGER"
+ case LongType => "BIGINT"
+ case _ => dataType.typeName
+ })
+ // Spark truncates toward zero when casting a fractional value to an
integral type, but many
+ // databases round instead, so a pushed down cast can return a different
result than Spark.
+ // Dialects for such databases override `truncateFractionalValue` to
truncate the value first.
+ val castedExpr = if (exprDataType.isInstanceOf[FractionalType] &&
+ dataType.isInstanceOf[IntegralType] &&
+ !SQLConf.get.legacyJdbcRoundIntegralCastPushdown) {
Review Comment:
**Non-blocking (P2):** The conf is checked only here and in MySQL's
fractional case, around the truncating function. The new type spellings above
and MySQL's `SIGNED` rendering apply whatever the conf says. The previous
version sent a BIGINT target to Postgres as `CAST(x AS long)` and every
integral target to MySQL as `INTEGER`, `BIGINT`, `SMALLINT` or `TINYINT`, which
those databases reject: pushed filters failed, and aggregates fell back to
Spark after the failed probe query, so Spark computed the truncated result.
With the conf on, the same queries now run on the database and round. For
example, `SUM(CAST(d AS INT))` over 1.6, 2.6 and -1.6 on MySQL is pushed as
``SUM(CAST(`d` AS SIGNED))`` and would return 3, which the new V2JDBCTest
legacy block asserts, where the previous version returned 2. Turning the conf
on therefore does not give users the previous results back.
**Recommended change:** With the conf on, make the shared visitCast spell an
unmapped target with Spark's type name as the base branch did, so a Postgres
BIGINT target is sent as `long` again, and make MySQLSQLBuilder.visitCast pass
integral targets to the shared visitCast as the base branch did, so the on
state reproduces the base branch's pushed SQL for every integral cast. Update
the conf's doc to say it restores the previous pushed SQL, including that casts
the previous version could not run fail again, and update the conf-on
expectations in the compiled-SQL tests and the docker legacy block, which on
MySQL should expect the base branch's outcome instead of rounding.
**Why this works:** The conf selects between two complete renderings instead
of toggling one part of the new one: off renders the change's SQL, on renders
the base branch's SQL, so the rollback cannot produce SQL that neither version
sent.
**Scope:** Gate the whole new integral cast rendering on the legacy conf and
align its doc and tests with the base branch's SQL.
**Compatibility:** With the conf off, every dialect's pushed SQL stays as
the rest of the change renders it.
**Risks:** With the conf on, pushed casts to BIGINT on Postgres, SQL Server
and DB2 and every integral cast on MySQL fail again as on the base branch, so
users who set the conf get the old failures with the old rounding, which the
updated doc states.
**Constraints:** With the conf off, the new SQL type names, MySQL's SIGNED
rendering and the truncating function stay as the rest of the change leaves
them. MySQL's rule for which sources may be sent as SIGNED applies only with
the conf off, since with the conf on MySQL's integral casts take the base
branch's path.
**Success:** With the conf on, every pushed integral cast compiles to the
SQL the base branch sent, for example Postgres `CAST("a" AS integer)` and
`CAST("a" AS long)`, Oracle `CAST("a" AS NUMBER(10))` and MySQL ``CAST(`a` AS
INTEGER)``. With the conf on, SUM(CAST(d AS INT)) on MySQL is not pushed down,
because MySQL rejects the probe query, and returns Spark's truncated result, as
on the base branch. The conf's doc describes its on state as the previous
pushed SQL.
**Verification:**
- **Compatibility:** Compiled-SQL coverage with the conf on shows the base
branch's SQL for each changed dialect: Spark's type names for unmapped SMALLINT
and BIGINT targets, MySQL's INTEGER, BIGINT, SMALLINT and TINYINT targets, and
no truncating function.
- **Regression:** Against MySQL with the conf on, SUM(CAST(d AS INT)) over
1.6, 2.6 and -1.6 returns 2 without the aggregate being pushed down, as on the
base branch, while against Postgres and Oracle with the conf on a pushed filter
on CAST(d AS INT) still matches by rounding.
##########
sql/core/src/test/scala/org/apache/spark/sql/jdbc/JDBCSuite.scala:
##########
@@ -1397,6 +1397,58 @@ class JDBCSuite extends SharedSparkSession {
assert(msSqlServer.compileExpression(bareIsNull).get === "\"a\" IS NULL")
}
+ test("fractional to integral cast pushdown is wrapped in the dialect
truncating function " +
+ "when needed") {
+ val cast = new V2Cast(FieldReference("a"), DoubleType, IntegerType)
+
+ assert(JdbcDialects.get("jdbc:").compileExpression(cast).get ===
"""CAST("a" AS INTEGER)""")
+
+
assert(JdbcDialects.get("jdbc:postgresql://127.0.0.1/db").compileExpression(cast).get
===
+ """CAST(TRUNC("a") AS INTEGER)""")
+
assert(JdbcDialects.get("jdbc:oracle://127.0.0.1/db").compileExpression(cast).get
===
+ """CAST(TRUNC("a") AS NUMBER(10))""")
+
assert(JdbcDialects.get("jdbc:snowflake://127.0.0.1/db").compileExpression(cast).get
===
+ """CAST(TRUNC("a") AS INTEGER)""")
+
assert(JdbcDialects.get("jdbc:mysql://127.0.0.1/db").compileExpression(cast).get
===
+ "CAST(TRUNCATE(`a`, 0) AS SIGNED)")
+
+ withSQLConf(SQLConf.LEGACY_JDBC_ROUND_INTEGRAL_CAST_PUSHDOWN.key ->
"true") {
+
assert(JdbcDialects.get("jdbc:postgresql://127.0.0.1/db").compileExpression(cast).get
===
+ """CAST("a" AS INTEGER)""")
+
assert(JdbcDialects.get("jdbc:oracle://127.0.0.1/db").compileExpression(cast).get
===
+ """CAST("a" AS NUMBER(10))""")
+
assert(JdbcDialects.get("jdbc:snowflake://127.0.0.1/db").compileExpression(cast).get
===
+ """CAST("a" AS INTEGER)""")
+
assert(JdbcDialects.get("jdbc:mysql://127.0.0.1/db").compileExpression(cast).get
===
+ "CAST(`a` AS SIGNED)")
+ }
+ }
+
+ test("SPARK-58372: H2 truncates fractional to integral casts") {
+ val h2 = JdbcDialects.get("jdbc:h2:mem:testdb0")
+ Seq(DoubleType, DecimalType(10, 2)).foreach { from =>
+ val cast = new V2Cast(FieldReference("a"), from, IntegerType)
+ assert(h2.compileExpression(cast).get === """CAST(TRUNC("a") AS
INTEGER)""")
+ withSQLConf(SQLConf.LEGACY_JDBC_ROUND_INTEGRAL_CAST_PUSHDOWN.key ->
"true") {
+ assert(h2.compileExpression(cast).get === """CAST("a" AS INTEGER)""")
+ }
+ }
+ }
+
+ test("SPARK-58372: integral cast targets without a dialect mapping use SQL
type names") {
Review Comment:
**Nit (P3):** The fallback in `visitCast` respells only `ShortType`,
`IntegerType` and `LongType`. A `ByteType` target without a dialect mapping
still uses Spark's name, so the generic dialect compiles a TINYINT cast to
`CAST("a" AS byte)`. This test checks only BIGINT and SMALLINT, so the title
claims more than the code does. Narrowing it, and saying in the fallback
comment why a TINYINT target keeps `byte`, would keep the next reader from
assuming every integral target is covered:
```suggestion
test("SPARK-58372: unmapped SMALLINT, INTEGER and BIGINT cast targets use
SQL type names") {
```
**Verification:**
- **Inspection:** The test title no longer claims every integral cast
target, and the comment above the SQL type-name fallback explains why a TINYINT
target keeps Spark's type name.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -7627,6 +7627,18 @@ object SQLConf {
.booleanConf
.createWithDefault(false)
+ val LEGACY_JDBC_ROUND_INTEGRAL_CAST_PUSHDOWN =
+ buildConf("spark.sql.legacy.jdbc.roundIntegralCastPushdown.enabled")
Review Comment:
**Non-blocking (P2):** This conf is the only way back to the previous
pushed-down results, and the change alters default results on upgrade: a
Postgres `SUM(CAST(price AS INT))` that added rounded values in 4.3 adds
truncated ones in 4.4. The conf is `.internal()`, so it is not in the generated
configuration docs, and the PR adds no entry to the 'Upgrading from Spark SQL
4.3 to 4.4' section of `docs/sql-migration-guide.md`. The other JDBC legacy
confs that change default results, such as
`spark.sql.legacy.oracle.numberMapping.enabled` and
`spark.sql.legacy.postgres.datetimeMapping.enabled`, each have an entry there.
An entry that names the truncation change, the affected databases and this conf
as the way to restore the previous behavior would let users find both. On MySQL
the previous version's integral cast targets were rejected, so the entry would
say those casts failed or ran in Spark rather than that they rounded.
**Verification:**
- **Inspection:** The 4.3-to-4.4 migration notes contain one entry that
describes the truncation of pushed fractional-to-integral casts on PostgreSQL,
MySQL, Oracle, Snowflake and H2, says which previously failing casts now run as
the final change leaves them, and names
spark.sql.legacy.jdbc.roundIntegralCastPushdown.enabled as restoring the
previous behavior.
##########
sql/core/src/main/scala/org/apache/spark/sql/jdbc/MySQLDialect.scala:
##########
@@ -126,6 +130,11 @@ private case class MySQLDialect() extends JdbcDialect with
SQLConfHelper with No
// The common JDBC mapping is DOUBLE PRECISION, which is not a
portable CAST target for
// MySQL-compatible databases. In particular, MariaDB rejects it
with a syntax error.
throw new UnsupportedOperationException("Cannot cast to double type")
+ // MySQL does not support casting to SHORT, INT or BIGINT, it uses
SIGNED instead.
Review Comment:
**Nit (P3):** The cases below match every integral target, replacing the
TINYINT, SMALLINT, INTEGER and BIGINT targets that `getJDBCType` and the common
mapping produce. SHORT is not a MySQL type and TINYINT is not mentioned, so a
reader cannot tell that TINYINT and SMALLINT targets are rewritten too:
```suggestion
// MySQL has no TINYINT, SMALLINT, INTEGER or BIGINT CAST target; it
uses SIGNED instead.
```
**Verification:**
- **Inspection:** The comment above MySQL's integral cast cases names
TINYINT, SMALLINT, INTEGER and BIGINT and no longer names SHORT.
##########
sql/core/src/main/scala/org/apache/spark/sql/jdbc/MySQLDialect.scala:
##########
@@ -126,6 +130,11 @@ private case class MySQLDialect() extends JdbcDialect with
SQLConfHelper with No
// The common JDBC mapping is DOUBLE PRECISION, which is not a
portable CAST target for
// MySQL-compatible databases. In particular, MariaDB rejects it
with a syntax error.
throw new UnsupportedOperationException("Cannot cast to double type")
+ // MySQL does not support casting to SHORT, INT or BIGINT, it uses
SIGNED instead.
+ case _: IntegralType if exprDataType.isInstanceOf[FractionalType] &&
+ !conf.legacyJdbcRoundIntegralCastPushdown =>
+ s"CAST(${truncateFractionalValue(expr)} AS SIGNED)"
Review Comment:
**Non-blocking (P2):** Every DECIMAL source takes this branch, including a
MySQL BIGINT UNSIGNED column, which JDBC reads as `DecimalType(20, 0)`, and
DECIMAL columns with more than 18 integer digits. `SIGNED` is MySQL's 64-bit
signed integer, and neither this code nor MySQL's conversion raises an error
for a value outside its range. For a BIGINT UNSIGNED value of
18446744073709551615, `WHERE CAST(c AS BIGINT) < 0` would match the row and
`SUM(CAST(c AS BIGINT))` would add -1. For a DECIMAL(20, 0) value of 10^19,
`MAX(CAST(d AS BIGINT))` would return 9223372036854775807 with only a warning.
Spark's ANSI cast raises CAST_OVERFLOW for both values, and MySQL rejected the
previous version's BIGINT target, so these queries failed or ran in Spark. This
is the review's reading of mysql/mysql-server at mysql-9.6.0: TRUNCATE keeps
the unsigned flag, `CAST(... AS SIGNED)` reinterprets the value without a range
check, and DECIMAL-to-integer conversion clamps on overflow with only a
warning.
FLOAT and DOUBLE sources are not affected, because MySQL raises an
out-of-range error for them.
See **Shared repair plan 1** in the review body.
##########
sql/core/src/main/scala/org/apache/spark/sql/jdbc/JdbcDialects.scala:
##########
@@ -460,8 +460,24 @@ abstract class JdbcDialect extends Serializable with
Logging {
override def visitCast(expr: String, exprDataType: DataType, dataType:
DataType): String = {
val databaseTypeDefinition =
-
getJDBCType(dataType).map(_.databaseTypeDefinition).getOrElse(dataType.typeName)
- s"CAST($expr AS $databaseTypeDefinition)"
+ getJDBCType(dataType).map(_.databaseTypeDefinition).getOrElse(dataType
match {
+ // Spark's type names `short` and `long` are not valid SQL types in
most databases.
+ case ShortType => "SMALLINT"
+ case IntegerType => "INTEGER"
+ case LongType => "BIGINT"
+ case _ => dataType.typeName
+ })
+ // Spark truncates toward zero when casting a fractional value to an
integral type, but many
+ // databases round instead, so a pushed down cast can return a different
result than Spark.
+ // Dialects for such databases override `truncateFractionalValue` to
truncate the value first.
+ val castedExpr = if (exprDataType.isInstanceOf[FractionalType] &&
Review Comment:
**Nit (P3):** `DecimalType` of every scale is a `FractionalType`, so this
condition also wraps DECIMAL(p, 0) sources, whose values have no fractional
part. Examples are the Oracle NUMBER(10) and NUMBER(19) columns that Spark's
own Oracle mapping writes and reads back as DECIMAL(10, 0) and DECIMAL(19, 0),
and Postgres numeric(p, 0) columns. `SUM(CAST(id AS BIGINT))` on such an Oracle
column is now sent as `SUM(CAST(TRUNC("ID") AS NUMBER(19)))`, where the
previous SQL already returned Spark's result. Results do not change, but the
database now evaluates a no-op TRUNC for every row. Requiring FLOAT, DOUBLE or
a DECIMAL with a positive scale here, and in the matching MySQL case, would
keep the previous SQL for these sources.
See **Shared repair plan 2** in the review body.
##########
sql/core/src/main/scala/org/apache/spark/sql/jdbc/MySQLDialect.scala:
##########
@@ -126,6 +130,11 @@ private case class MySQLDialect() extends JdbcDialect with
SQLConfHelper with No
// The common JDBC mapping is DOUBLE PRECISION, which is not a
portable CAST target for
// MySQL-compatible databases. In particular, MariaDB rejects it
with a syntax error.
throw new UnsupportedOperationException("Cannot cast to double type")
+ // MySQL does not support casting to SHORT, INT or BIGINT, it uses
SIGNED instead.
+ case _: IntegralType if exprDataType.isInstanceOf[FractionalType] &&
+ !conf.legacyJdbcRoundIntegralCastPushdown =>
+ s"CAST(${truncateFractionalValue(expr)} AS SIGNED)"
+ case _: IntegralType => s"CAST($expr AS SIGNED)"
Review Comment:
**Non-blocking (P2):** This case renders every integral cast as `SIGNED`
whatever the source type, though only fractional sources need the new
rendering. In ANSI mode Spark also pushes casts from string, TIMESTAMP and TIME
sources, including the `CAST(s AS BIGINT)` that ANSI string promotion adds when
a string column is compared with an integer, and MySQL converts them by its own
rules: a TIMESTAMP becomes a YYYYMMDDHHMMSS number, a TIME becomes HHMMSS, and
a non-numeric string becomes 0 with only a warning. So `MAX(CAST(ts AS
BIGINT))` would return a value like 20231113123456 instead of Spark's epoch
seconds, `WHERE CAST(ts AS BIGINT) > 1700000000` would keep 2023 rows that
Spark drops, and `WHERE s = 0` on a VARCHAR column would match 'abc' where
Spark raises CAST_INVALID_INPUT. The previous version sent INTEGER, BIGINT,
SMALLINT or TINYINT targets, which MySQL rejects, so these filters failed and
these aggregates ran in Spark with the right results. The MySQL behavior is
from t
he review's reading of mysql/mysql-server at the mysql-9.6.0 tag the docker
suite pins (`Item_typecast_signed::val_int` in sql/item_func.cc).
See **Shared repair plan 1** in the review body.
##########
sql/core/src/main/scala/org/apache/spark/sql/jdbc/JdbcDialects.scala:
##########
@@ -460,8 +460,24 @@ abstract class JdbcDialect extends Serializable with
Logging {
override def visitCast(expr: String, exprDataType: DataType, dataType:
DataType): String = {
val databaseTypeDefinition =
-
getJDBCType(dataType).map(_.databaseTypeDefinition).getOrElse(dataType.typeName)
- s"CAST($expr AS $databaseTypeDefinition)"
+ getJDBCType(dataType).map(_.databaseTypeDefinition).getOrElse(dataType
match {
+ // Spark's type names `short` and `long` are not valid SQL types in
most databases.
+ case ShortType => "SMALLINT"
+ case IntegerType => "INTEGER"
+ case LongType => "BIGINT"
+ case _ => dataType.typeName
+ })
+ // Spark truncates toward zero when casting a fractional value to an
integral type, but many
+ // databases round instead, so a pushed down cast can return a different
result than Spark.
+ // Dialects for such databases override `truncateFractionalValue` to
truncate the value first.
+ val castedExpr = if (exprDataType.isInstanceOf[FractionalType] &&
+ dataType.isInstanceOf[IntegralType] &&
Review Comment:
**Nit (P3):** The new JDBCSuite cases pin the source-type and conf parts of
this condition, but not this target check: none compiles a fractional source
cast to a non-integral target. JDBCV2Suite's ANSI push-down test does push
`CAST(SALARY AS double)` and `cast(bonus as decimal(20, 2))`, but its H2 rows
are whole numbers and it compares V2 descriptions rather than compiled SQL. If
this check were dropped, Postgres would get `CAST(TRUNC("d") AS NUMERIC(10,2))`
for `CAST(d AS DECIMAL(10, 2))`, turning 1.6 into 1.00, and no test would fail.
One assertion, for example that `new V2Cast(FieldReference("a"), DoubleType,
DecimalType(10, 2))` compiles to `CAST("a" AS NUMERIC(10,2))` on Postgres,
would pin it.
See **Shared repair plan 2** in the review body.
--
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]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]