cloud-fan commented on code in PR #60455:
URL: https://github.com/apache/spark/pull/60455#discussion_r4617469286
##########
sql/core/src/main/scala/org/apache/spark/sql/jdbc/JdbcDialects.scala:
##########
@@ -459,11 +459,42 @@ 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)"
+ val mappedType = getJDBCType(dataType).map(_.databaseTypeDefinition)
+ val legacyIntegralCastPushdown = JdbcUtils.legacyIntegralCastPushdown
+ if (!legacyIntegralCastPushdown &&
exprDataType.isInstanceOf[DatetimeType] &&
+ dataType.isInstanceOf[IntegralType]) {
Review Comment:
**Non-blocking (P2):** This check only refuses integral targets, but in ANSI
mode Spark also casts TIMESTAMP to DOUBLE, FLOAT and DECIMAL, and TIME to
DECIMAL, and those casts still take the unchanged `else` branch and are pushed
under the database's own conversion. This review ran the MySQL case on MySQL
9.6.0: for a TIMESTAMP column holding 2023-11-13 and 2023-11-15, ``CAST(`ts` AS
DECIMAL(20,0))`` returned 20231113000000 and 20231115000000, so the pushed
filter ``CAST(`ts` AS DECIMAL(20,0)) < 1700000000`` returned no row, where
Spark's epoch seconds (1699833600 and 1700006400) keep the 2023-11-13 row. The
same query with `BIGINT` is now refused and evaluated by Spark, so users get
Spark's result for one numeric target and silently wrong rows for another. SQL
Server, which gets TIMESTAMP columns from Spark as DATETIME, documents the same
day-count conversion for `float` that the refusal cites for integral targets.
See **Shared repair plan 1** in the review body.
##########
sql/core/src/main/scala/org/apache/spark/sql/jdbc/JdbcDialects.scala:
##########
@@ -459,11 +459,42 @@ 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)"
+ val mappedType = getJDBCType(dataType).map(_.databaseTypeDefinition)
+ val legacyIntegralCastPushdown = JdbcUtils.legacyIntegralCastPushdown
+ if (!legacyIntegralCastPushdown &&
exprDataType.isInstanceOf[DatetimeType] &&
Review Comment:
**Non-blocking (P2):** This guard runs before any dialect logic, so it also
refuses the Databricks dialect, whose remote evaluates `CAST` with Spark's own
semantics. On the base branch, `WHERE CAST(ts AS BIGINT) > 1700000000` over a
`jdbc:databricks` catalog went to the remote as ``CAST(`ts` AS long) >
1700000000``, which Spark SQL accepts and evaluates as Spark does; TIMESTAMP to
BIGINT is also an up-cast, so it is pushed in every session mode. With this
change the predicate stays in a Spark `Filter`, the scan fetches every row, and
the remaining filter also stops a `COUNT(*)`, `LIMIT` or top-N over it from
being pushed. Results stay correct, but the extra transfer grows with the
table, and the only way back is the internal legacy setting, which also
restores rounding on every other database. The reason in the comment, that
databases convert datetimes to numbers differently, does not apply to a
database whose cast is Spark's.
See **Shared repair plan 1** in the review body.
##########
sql/core/src/main/scala/org/apache/spark/sql/jdbc/JdbcDialects.scala:
##########
@@ -459,11 +459,42 @@ 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)"
+ val mappedType = getJDBCType(dataType).map(_.databaseTypeDefinition)
+ val legacyIntegralCastPushdown = JdbcUtils.legacyIntegralCastPushdown
+ if (!legacyIntegralCastPushdown &&
exprDataType.isInstanceOf[DatetimeType] &&
+ dataType.isInstanceOf[IntegralType]) {
+ // Spark and databases convert datetimes to numbers differently.
+ cannotPushCast(exprDataType, dataType)
+ }
+ if (!legacyIntegralCastPushdown && isFractionalToIntegral(exprDataType,
dataType)) {
+ val databaseTypeDefinition = mappedType.getOrElse(dataType match {
+ // Spark's names `short` and `long` aren't valid SQL types. TINYINT
isn't portable either,
+ // so ByteType keeps Spark's name.
+ case ShortType => "SMALLINT"
+ case IntegerType => "INTEGER"
+ case LongType => "BIGINT"
+ case _ => dataType.typeName
+ })
+ s"CAST(${truncateFraction(expr, exprDataType)} AS
$databaseTypeDefinition)"
+ } else {
+ s"CAST($expr AS ${mappedType.getOrElse(dataType.typeName)})"
Review Comment:
**Nit (P3):** Only the fractional branch above explains why Spark's `short`
and `long` are respelled. This branch still emits
`mappedType.getOrElse(dataType.typeName)`, so a STRING-to-BIGINT cast compiles
to `CAST("a" AS long)` on the generic and Postgres dialects, which those
databases reject. The PR description says casts from other types keep the
previous SQL on purpose, but nothing in the code says so, so a later reader may
extend the respelling to these sources or treat the gap as an oversight. A
short comment or TODO naming the non-fractional sources that keep Spark's type
names, and why, would record the intent.
**Verification:**
- **Inspection:** The else branch of the shared JDBC cast rendering has a
comment that names the non-fractional sources keeping Spark's type names, says
those casts are still rejected where the target is unmapped, and gives the
reason.
##########
docs/sql-migration-guide.md:
##########
@@ -100,6 +100,7 @@ license: |
- Since Spark 4.4, a CHECK constraint that `ALTER TABLE ... ADD CONSTRAINT`
adds to a Data Source V2 table, and whose condition reads the current time,
date, catalog, user and the like, such as `ts <= current_timestamp()` or `db =
current_database()`, is checked against their values at the time of each write.
Previously, it was checked against their values at the time of the `ALTER
TABLE`, unless a write could not read back a predicate for its condition, such
as one with a lambda function or one that passes a column to `datediff`, `year`
or `upper` (SPARK-60032). Such a constraint is stored without a predicate, so
each write parses and analyzes its SQL text under the session of the write, as
it does for a constraint without a predicate that `CREATE TABLE` adds. A
setting of the write such as `spark.sql.ansi.enforceReservedKeywords`, which
reserves `TIME`, or `spark.sql.ansi.doubleQuotedIdentifiers` can then make it
fail to parse the text or read it differently. A row-level operation
that copies unchanged rows, such as a `DELETE` or `UPDATE` on a copy-on-write
table, fails with `CHECK_CONSTRAINT_VIOLATION` on a copied row that no longer
satisfies the condition. For example, `ts >= current_timestamp() - INTERVAL 30
DAYS` now fails such a `DELETE` once a copied row is older than 30 days. A
condition that Spark detects a write could resolve differently is stored as
before, so a write accepts and rejects the same rows for it as before. Examples
are conditions that also read a variable, a `CHAR` column, a name with more
than one part such as a column qualified by the table name, or a constant that
depends on the session time zone, such as `'2024-01-01 00:00:00'` cast to a
timestamp. So are conditions with a name such as `current_date` or `user`
without parentheses, which a write can read as a column name, and conditions
whose text the parser settings of the `ALTER TABLE`, such as
`spark.sql.ansi.doubleQuotedIdentifiers` or
`spark.sql.parser.escapedStringLiterals`, r
ead differently from their default values. ANSI mode,
`spark.sql.timestampType` and the session time zone are taken from the session
for this comparison, as for a generation expression. A condition that reads the
current date or time only through a typed literal such as `DATE 'today'` is
also stored as before. An existing constraint keeps its stored predicate until
it is dropped and added again. `Check.predicate()` is null for a constraint
stored without a predicate, so a connector that validates or enforces it itself
has to evaluate `Check.predicateSql()`. To restore the previous behavior, set
`spark.sql.legacy.freezeCurrentValuesInCheckConstraint` to `true` before adding
the constraint. A constraint added without it is not changed.
- Since Spark 4.4, a function created by `CREATE FUNCTION ... AS 'class'`
whose class implements
`org.apache.spark.sql.connector.catalog.functions.UnboundFunction` and extends
either a Hive UDF class (such as `UDF` or `GenericUDF`) or
`org.apache.spark.sql.expressions.UserDefinedAggregateFunction` runs as a
DataSource V2 function instead of a Hive UDF or Spark UDAF, including functions
created in earlier versions. Its result type, argument coercion, and null
handling are defined by the V2 implementation selected by
`UnboundFunction.bind`. Hive's `@UDFType` and Spark UDAF's `deterministic`
property do not control the V2 path. For scalar functions, determinism uses
`BoundFunction.isDeterministic()` (default `true`) and the arguments'
determinism. A call with constant arguments can therefore become eligible for
constant folding during query planning instead of being evaluated per row.
- Since Spark 4.4, `next_day` and `last_day` fail with `DATETIME_OVERFLOW`
when the result is later than the maximum `DATE`, `+5881580-07-11`, and `trunc`
fails with it when the result is earlier than the minimum `DATE`,
`-5877641-06-23`, regardless of `spark.sql.ansi.enabled`. Previously, these
functions silently returned a wrong date, in most cases one at the other end of
the `DATE` range; for example, `last_day(DATE'+5881580-07-11')` returned
`-5877641-07-12` and `trunc(DATE'-5877641-06-23', 'MONTH')` returned
`+5881580-06-20`, while `trunc` to `QUARTER` failed with `ARITHMETIC_OVERFLOW`.
`next_day` and `trunc` to `WEEK` also returned a wrong date for the first days
of the `DATE` range; for example, `next_day(DATE'-5877641-06-23', 'MO')` and
`trunc(DATE'-5877641-07-01', 'WEEK')` returned `-5877641-06-25`, a Thursday,
and now return `-5877641-06-29`.
+- Since Spark 4.4, a cast from `FLOAT`, `DOUBLE` or `DECIMAL` to an integral
type that is pushed down to a JDBC data source truncates toward zero, as Spark
does. Previously, PostgreSQL, Oracle, Snowflake, H2, and SQL Server for `MONEY`
and `SMALLMONEY` columns rounded such casts, so pushed-down filters, aggregates
and sort keys could return different results than Spark. On dialects without a
mapping for the target type, these casts use the SQL type names `SMALLINT`,
`INTEGER` and `BIGINT` instead of Spark's type names such as `long`, which
databases rejected. MySQL receives only such casts to `BIGINT` from `DECIMAL`
values that always fit in 64 bits, and Spark evaluates the others, which MySQL
rejected before. Casts from `DATE`, `TIMESTAMP` and `TIME` values to integral
types are no longer pushed down. To restore the previous pushed-down SQL, set
`spark.sql.legacy.jdbc.roundIntegralCastPushdown.enabled` to `true`.
Review Comment:
**Nit (P3):** In "Casts from `DATE`, `TIMESTAMP` and `TIME` values to
integral types are no longer pushed down", the `DATE` part describes no change:
a DATE-to-integral cast is neither an ANSI cast (`Cast.canAnsiCast` has no
DATE-to-numeric case) nor an up-cast, so Spark never translated one for
pushdown, before or after this PR. Naming only `TIMESTAMP` and `TIME` would
keep users from reading it as a change for DATE columns.
**Verification:**
- **Inspection:** The 4.3-to-4.4 migration entry for pushed casts names only
TIMESTAMP and TIME as the datetime sources whose casts are no longer pushed
down.
##########
sql/core/src/test/scala/org/apache/spark/sql/jdbc/JDBCSuite.scala:
##########
@@ -1397,6 +1397,154 @@ class JDBCSuite extends SharedSparkSession {
assert(msSqlServer.compileExpression(bareIsNull).get === "\"a\" IS NULL")
}
+ test("SPARK-58372: fractional to integral cast pushdown is wrapped in the
dialect truncating " +
+ "function when needed") {
+ val cast = new V2Cast(FieldReference("a"), DoubleType, IntegerType)
+ val mysqlCast = new V2Cast(FieldReference("a"), DecimalType(10, 2),
LongType)
+
+ 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(mysqlCast).get
===
+ "CAST(TRUNCATE(`a`, 0) AS SIGNED)")
+
assert(JdbcDialects.get("jdbc:sqlserver://127.0.0.1/db").compileExpression(cast).get
===
+ """CAST(ROUND("a", 0, 1) AS INTEGER)""")
+
+ // The legacy conf restores the previous pushed SQL, including Spark's
type names.
+ 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 INTEGER)")
+
assert(JdbcDialects.get("jdbc:mysql://127.0.0.1/db").compileExpression(mysqlCast).get
===
+ "CAST(`a` AS BIGINT)")
+
assert(JdbcDialects.get("jdbc:sqlserver://127.0.0.1/db").compileExpression(cast).get
===
+ """CAST("a" AS integer)""")
+ val fromTimestamp = new V2Cast(FieldReference("a"), TimestampType,
LongType)
+
assert(JdbcDialects.get("jdbc:sqlserver://127.0.0.1/db").compileExpression(fromTimestamp)
+ .get === """CAST("a" AS long)""")
+ }
+ }
+
+ test("SPARK-58372: fractional to integral casts truncate through
AggregatedDialect") {
+ val custom = new JdbcDialect {
+ override def canHandle(url: String): Boolean =
url.startsWith("jdbc:postgresql")
+ }
+ val cast = new V2Cast(FieldReference("a"), DoubleType, IntegerType)
+ Seq(
+ new AggregatedDialect(List(custom, PostgresDialect())),
+ new AggregatedDialect(List(PostgresDialect(), custom))
+ ).foreach { d =>
+ assert(d.compileExpression(cast).get === """CAST(TRUNC("a") AS
INTEGER)""", s"dialect=$d")
+ }
+ assert(new AggregatedDialect(List(custom,
NoopDialect)).compileExpression(cast).get ===
+ """CAST("a" AS INTEGER)""")
+ }
+
+ test("SPARK-58372: integral casts of datetime sources are not pushed down") {
+ Seq("jdbc:", "jdbc:postgresql://127.0.0.1/db",
"jdbc:sqlserver://127.0.0.1/db",
+ "jdbc:db2://127.0.0.1/db", "jdbc:oracle://127.0.0.1/db",
"jdbc:h2:mem:testdb0",
+ "jdbc:mysql://127.0.0.1/db", "jdbc:snowflake://127.0.0.1/db"
+ ).foreach { url =>
+ for (from <- Seq(TimestampType, TimestampNTZType, DateType);
Review Comment:
**Nit (P3):** This loop covers `TimestampType`, `TimestampNTZType` and
`DateType`, but not `TimeType`, the other datetime source that
`Cast.canAnsiCast` lets reach a pushed integral cast. The guard refuses TIME
only because `TimeType` extends `AnyTimeType`, which extends `DatetimeType`, so
a guard rewritten to list `TimestampType | TimestampNTZType | DateType`, or to
test `AnyTimestampType` and `DateType`, would push `CAST(t AS BIGINT)` for a
TIME column again and still pass this test. Adding `TimeType()` to the sources
would pin it; the `TimestampNTZType` and `DateType` rows are worth keeping,
since they catch a guard narrowed to `TimestampType`.
**Verification:**
- **Regression:** Compiled-SQL coverage shows a TIME source cast to TINYINT,
SMALLINT, INT and BIGINT compiling to nothing on each dialect the test lists,
so a guard that names TIMESTAMP, TIMESTAMP_NTZ and DATE but not TIME fails it.
##########
sql/core/src/main/scala/org/apache/spark/sql/jdbc/MsSqlServerDialect.scala:
##########
@@ -66,6 +66,10 @@ private case class MsSqlServerDialect() extends JdbcDialect
with NoLegacyJDBCErr
override def isSupportedFunction(funcName: String): Boolean =
supportedFunctions.contains(funcName)
+ // SQL Server rounds MONEY and SMALLMONEY (read as DECIMAL) when casting to
an integral type.
+ // ROUND with a nonzero third argument truncates instead.
+ override def truncateFractionalValue(expr: String): String = s"ROUND($expr,
0, 1)"
Review Comment:
**Nit (P3):** The comment above justifies the wrapper only for MONEY and
SMALLMONEY, which Spark reads as DECIMAL, but this override applies to every
fractional source. A FLOAT or REAL column cast to INT is now sent as
`CAST(ROUND("f", 0, 1) AS INTEGER)` instead of the base branch's `CAST("f" AS
integer)`, which SQL Server already truncates. The result is the same, but SQL
Server evaluates an extra function call for every row the pushed filter,
aggregate or sort key touches. Since `MsSqlServerSQLBuilder` extends
`JDBCSQLBuilder`, overriding the protected `truncateFraction` there to wrap
only `DecimalType` sources would keep MONEY and SMALLMONEY truncated and leave
FLOAT and REAL on the plain cast; the JDBCSuite expectation for the DOUBLE
source would change with it.
**Verification:**
- **Behavior:** Compiled-SQL coverage for the SQL Server dialect shows
DOUBLE and FLOAT sources cast to INT and BIGINT without ROUND, and a
DECIMAL(19, 4) source cast to INT with ROUND(x, 0, 1).
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JDBCOptions.scala:
##########
@@ -283,6 +283,9 @@ class JDBCOptions(
.map(_.toBoolean)
.getOrElse(dialectTimestampNTZAsWallClock)
+ // Resolved once, so tasks compile pushed predicates under the value
pushdown used.
+ val legacyIntegralCastPushdown: Boolean =
SQLConf.get.legacyJdbcRoundIntegralCastPushdown
Review Comment:
**Non-blocking (P2):** This value is read when `JDBCTable.newScanBuilder`
builds the scan, and `JDBCRDD` compiles the task predicates under it, but the
pushdown-time compile sites in `JDBCScanBuilder` (`pushPredicates`,
`pushAggregation`, `pushDownJoin` and `pushTopN`) call `compileExpression`
outside `withLegacyIntegralCastPushdown`, so `visitCast` reads the live session
setting there. If another thread sharing the session, such as a second Spark
Connect operation, flips the setting between building the scan and pushing its
predicates, the two phases disagree. Reading the code, with the setting
captured as false and flipped to true before `pushPredicates`, `CAST(time1 AS
BIGINT) < 0` would be accepted as pushed and Spark would drop its `Filter`, but
the tasks would refuse the cast, `withPredicates` would leave it out of the
WHERE clause, and every row would come back. Wrapping those compile calls in
`JdbcUtils.withLegacyIntegralCastPushdown(jdbcOptions.legacyIntegralCastPushdown)
` would let the captured value decide both phases.
**Verification:**
- **Regression:** For a scan whose JDBC options captured the legacy setting
off, pushing a TIMESTAMP-to-BIGINT predicate while the session value is on
leaves it unpushed, and pushing a fractional-to-integral predicate while the
session value is on keeps the truncating function in the SQL; the reverse
direction, captured on and live off, keeps the base branch's SQL at pushdown as
in the tasks.
##########
sql/core/src/main/scala/org/apache/spark/sql/jdbc/JdbcDialects.scala:
##########
@@ -459,11 +459,42 @@ 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)"
+ val mappedType = getJDBCType(dataType).map(_.databaseTypeDefinition)
+ val legacyIntegralCastPushdown = JdbcUtils.legacyIntegralCastPushdown
+ if (!legacyIntegralCastPushdown &&
exprDataType.isInstanceOf[DatetimeType] &&
+ dataType.isInstanceOf[IntegralType]) {
+ // Spark and databases convert datetimes to numbers differently.
+ cannotPushCast(exprDataType, dataType)
+ }
+ if (!legacyIntegralCastPushdown && isFractionalToIntegral(exprDataType,
dataType)) {
+ val databaseTypeDefinition = mappedType.getOrElse(dataType match {
+ // Spark's names `short` and `long` aren't valid SQL types. TINYINT
isn't portable either,
+ // so ByteType keeps Spark's name.
+ case ShortType => "SMALLINT"
+ case IntegerType => "INTEGER"
+ case LongType => "BIGINT"
Review Comment:
**Non-blocking (P2):** This respelling applies on every dialect, but
`truncateFractionalValue` returns its operand unchanged unless the dialect
overrides it. So on dialects that keep the default (`NoopDialect` for every URL
no dialect handles, Teradata, and third-party dialects that keep the default
`compileExpression`), a fractional cast to an unmapped BIGINT or SMALLINT
target now runs under the database's own conversion. On the base branch the
same cast went out as `CAST("d" AS long)`, which such databases reject, so a
pushed filter failed and a pushed aggregate fell back to Spark when the `WHERE
1=0` probe in `JDBCScanBuilder.pushAggregation` failed. This review ran the SQL
on Trino 484, which `NoopDialect` serves for `jdbc:trino` URLs: the base
branch's `CAST("d" AS long) = 2` failed with `Unknown type: long`, while
`CAST("d" AS BIGINT) = 2` over 1.6, 2.6 and -1.6 returned the 1.6 row instead
of Spark's 2.6 row, and `SUM(CAST("d" AS BIGINT))` returned 3 where Spark
returns 2.
A truncating control, `CAST(truncate("d") AS BIGINT)`, and embedded Derby
both returned Spark's row and sum. For databases that round, this turns a loud
failure, or Spark's correct aggregate, into a silently wrong result, and the
migration note's claim that such pushed casts truncate does not hold there.
INTEGER targets already ran as `CAST(x AS integer)` on the base branch, so only
SMALLINT and BIGINT targets change.
**Recommended change:** Add a JdbcDialect method, public and @Since 4.4.0
like truncateFractionalValue, that declares that the database's own cast to an
integral type truncates toward zero, with a default of false; override it to
true in the DB2, Derby and Databricks dialects, and forward it in
AggregatedDialect as true when any member returns true. In
JDBCSQLBuilder.visitCast (JdbcDialects.scala:469-478), spell an unmapped
integral target of a fractional cast with its SQL type name only when the
dialect's truncateFractionalValue changes its operand or the new method returns
true, and otherwise with Spark's type name, as the base branch did, so the
generic-dialect expectations at JDBCSuite.scala:1405 and 1449-1450 become
CAST("a" AS integer). Say on truncateFractionalValue and the new method that a
dialect keeping both defaults keeps the base branch's SQL, update the JDBCSuite
type-name test so the generic and Teradata dialects keep `long` and `short`
while DB2, Derby and Databric
ks get BIGINT and SMALLINT, and limit the migration entry's truncation claim
to the dialects that truncate.
**Why this works:** Which dialects send SQL type names moves from every
dialect to the dialects whose database is known to truncate: a dialect with its
own truncating function or with the new declaration gets BIGINT and SMALLINT,
which its database runs and truncates, while every other dialect keeps the SQL
the base branch sent, which a database that rejects Spark's names still
rejects, so a cast whose rounding Spark does not know keeps failing loudly or,
in an aggregate, is evaluated by Spark.
**Compatibility:** Dialects that override truncateFractionalValue, MySQL's
admission rule, the datetime refusal and casts from non-fractional sources keep
the behavior the rest of the change gives them.
**Risks:** Teradata and third-party dialects for databases that truncate
keep the base branch's failing SQL for fractional casts to BIGINT and SMALLINT
until they declare truncation, so those queries fail as they did on the base
branch. The new public JdbcDialect method becomes a compatibility commitment
once 4.4.0 ships.
**Constraints:** The respelling decision reads the dialect-level
truncateFractionalValue, not a SQL builder's truncateFraction, so a builder
that skips the truncating function for some sources, as the SQL Server repair
does for FLOAT and REAL, still sends SQL type names. With the legacy setting
on, every cast keeps the SQL the base branch sent. MySQL's own rendering of
fractional-to-integral casts is unchanged.
**Exclusions:**
- Fractional casts to INTEGER targets on dialects at the default already ran
under the database's own conversion on the base branch, as CAST(x AS integer),
and keep doing so, since truncating them needs a truncating function for each
database.
**Verification:**
- **Behavior:** Compiled-SQL coverage shows DOUBLE and DECIMAL(10, 2)
sources cast to BIGINT and SMALLINT compiling to Spark's `long` and `short` on
the generic and Teradata dialects and on a custom dialect that keeps both
defaults, and to BIGINT and SMALLINT on the DB2, Derby, Databricks and Postgres
dialects.
- **Regression:** An aggregated dialect of a custom dialect and the DB2
dialect compiles a DOUBLE-to-BIGINT cast to CAST("a" AS BIGINT), and one of a
custom dialect and NoopDialect compiles it to CAST("a" AS long).
- **Inspection:** The migration entry and the docs of
truncateFractionalValue and the new method name the dialects whose pushed
fractional casts truncate and say that other dialects keep the base branch's
SQL.
##########
sql/core/src/main/scala/org/apache/spark/sql/jdbc/MySQLDialect.scala:
##########
@@ -121,11 +125,21 @@ private case class MySQLDialect() extends JdbcDialect
with SQLConfHelper with No
}
override def visitCast(expr: String, exprDataType: DataType, dataType:
DataType): String = {
+ lazy val fractionalToIntegral = !JdbcUtils.legacyIntegralCastPushdown &&
+ isFractionalToIntegral(exprDataType, dataType)
dataType match {
case DoubleType =>
// 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's only integral CAST target is 64-bit SIGNED, and MariaDB
clamps values out of its
+ // range, so of the fractional casts only BIGINT from a DECIMAL that
always fits is pushed.
+ case LongType if fractionalToIntegral && (exprDataType match {
+ case d: DecimalType => d.precision - d.scale <=
Decimal.MAX_LONG_DIGITS
+ case _ => false
+ }) =>
+ s"CAST(${truncateFraction(expr, exprDataType)} AS SIGNED)"
+ case _: IntegralType if fractionalToIntegral =>
cannotPushCast(exprDataType, dataType)
Review Comment:
**Non-blocking (P2):** This case refuses every fractional cast to INT,
SMALLINT or TINYINT, including casts from `DECIMAL(p, 0)` columns with p <= 9,
whose values always fit INT. The MySQL dialect also serves MariaDB, and MariaDB
accepts the base branch's `CAST(x AS INTEGER)`: on MariaDB 10.11 this review
observed `CAST(d9 AS INTEGER) = 5` on a `DECIMAL(9, 0)` column returning the
matching row, while MySQL 9.6.0 rejects the same SQL. For MariaDB users, this
refusal turns a correct pushed filter, aggregate or sort key into Spark
evaluation after fetching every row. The reason given for refusing narrower
targets, that `SIGNED` has no range check for them, covers only DECIMALs that
can exceed the target's range: for a `DECIMAL(10, 2)` column holding 1.6, 2.6
and -1.6, ``CAST(TRUNCATE(`d`, 0) AS SIGNED)``, the form already sent for
BIGINT targets, returned 1, 2 and -1 on both servers. The migration entry is
also off for MariaDB: the base branch's `CAST(x AS INTEGER)` ran there and rou
nded 1.6 to 2 instead of being rejected. The pinned `mariadb:12.2.2` image
would not start on this host, so the run used 10.11.
**Recommended change:** In MySQLSQLBuilder.visitCast
(MySQLDialect.scala:135-142), push a fractional-to-integral cast from a DECIMAL
to any integral target whose range its integer digits always fit, precision
minus scale at most 2 for TINYINT, 4 for SMALLINT, 9 for INT and 18 for BIGINT,
as CAST(TRUNCATE(x, 0) AS SIGNED), or CAST(x AS SIGNED) for scale 0, and keep
refusing FLOAT and DOUBLE sources and wider DECIMALs. Update the comment above
it, the MySQL admission test in JDBCSuite (JDBCSuite.scala:1516-1546), the
MySQL docker suite's pushesIntegralCast override and the migration entry, which
then says that MySQL receives such casts from DECIMALs whose integer digits fit
the target and that MariaDB, which accepted the base branch's INTEGER target,
rounded casts to INT before.
**Why this works:** The range bound moves from one target to each target:
SIGNED returns a 64-bit value with no range check, so a DECIMAL whose integer
digits always fit the target gives Spark's value after TRUNCATE, and Spark
casts a pushed aggregate's output back to the target type, while sources that
can exceed the target's range stay in Spark.
**Compatibility:** BIGINT targets, the datetime refusal and casts from
non-fractional sources keep the behavior the rest of the change gives them.
**Risks:** On MySQL, which rejected these casts on the base branch, filters,
aggregates and sort keys over casts of fitting DECIMALs to INT, SMALLINT and
TINYINT are now pushed instead of evaluated by Spark, with the same results.
**Constraints:** FLOAT and DOUBLE sources and DECIMALs whose integer digits
can exceed the target's range stay in Spark, so no pushed cast can overflow.
With the legacy setting on, MySQL's casts keep the base branch's SQL. The
comment keeps describing SIGNED as MySQL's only signed integral CAST target.
**Verification:**
- **Behavior:** Compiled-SQL coverage for the MySQL dialect shows DECIMAL(9,
0) to INT compiling to CAST(`a` AS SIGNED) and DECIMAL(10, 2) to INT to
CAST(TRUNCATE(`a`, 0) AS SIGNED), while DECIMAL(10, 0) to INT, DECIMAL(5, 0) to
SMALLINT, DECIMAL(3, 0) to TINYINT and FLOAT and DOUBLE sources to every
integral target compile to nothing.
- **Regression:** In the MySQL docker suite, the shared integral-cast test
pushes the INT and BIGINT casts of its DECIMAL(10, 2) column and returns
Spark's truncated rows and sum.
- **Inspection:** The 4.3-to-4.4 migration entry names the DECIMAL casts
that MySQL-compatible databases receive and says that MariaDB rounded
fractional casts to INT before.
##########
sql/core/src/main/scala/org/apache/spark/sql/jdbc/MySQLDialect.scala:
##########
@@ -121,11 +125,21 @@ private case class MySQLDialect() extends JdbcDialect
with SQLConfHelper with No
}
override def visitCast(expr: String, exprDataType: DataType, dataType:
DataType): String = {
+ lazy val fractionalToIntegral = !JdbcUtils.legacyIntegralCastPushdown &&
+ isFractionalToIntegral(exprDataType, dataType)
dataType match {
case DoubleType =>
// 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's only integral CAST target is 64-bit SIGNED, and MariaDB
clamps values out of its
Review Comment:
**Nit (P3):** MySQL's `CAST` also accepts `UNSIGNED`, so "MySQL's only
integral CAST target is 64-bit SIGNED" is not literally true; the reasoning
holds for Spark's signed integral types, which `UNSIGNED` cannot represent.
Saying "MySQL's only signed integral CAST target is 64-bit SIGNED" here, and
likewise in the `pushesIntegralCast` comment at V2JDBCTest.scala:1370 ("MySQL
can only cast to 64-bit SIGNED"), would make both exact.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60455#discussion_r4569837979).
**Verification:**
- **Inspection:** The MySQL cast comment in MySQLDialect.scala and the
pushesIntegralCast comment in V2JDBCTest.scala describe SIGNED as MySQL's only
signed integral CAST target.
--
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]