This is an automated email from the ASF dual-hosted git repository.

uros-b pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.x by this push:
     new 8f8d37b346d8 [SPARK-61032][SQL] Do not push TopN to MySQL when 
ONLY_FULL_GROUP_BY rejects its sort keys
8f8d37b346d8 is described below

commit 8f8d37b346d8c04ad08bcb3b41d61b6ec27324dd
Author: aleksandar-trajkovic-db <[email protected]>
AuthorDate: Tue Nov 10 09:23:00 2026 +0000

    [SPARK-61032][SQL] Do not push TopN to MySQL when ONLY_FULL_GROUP_BY 
rejects its sort keys
    
    ### What changes were proposed in this pull request?
    Add `JdbcDialect.supportsTopN(orders, aggregation)`, consulted by 
`JDBCScanBuilder.pushTopN`. `MySQLDialect` refuses the sort keys MySQL's 
`ONLY_FULL_GROUP_BY` rejects; the aggregate stays pushed and Spark sorts and 
limits locally. The internal conf 
`spark.sql.legacy.mysql.topNOverGroupByExpr.enabled` restores the old pushdown, 
for servers that disable `ONLY_FULL_GROUP_BY`.
    
    ### Why are the changes needed?
    1. Goal: `ORDER BY ... LIMIT` over a pushed GROUP BY expression succeeds on 
MySQL.
    2. Problem: TopN sort keys are rewritten to the GROUP BY expressions, and 
MySQL's default `ONLY_FULL_GROUP_BY` rejects a term built over one:
    ```sql
    SELECT k + 1, COUNT(*) FROM mysql.db.t GROUP BY k + 1 ORDER BY (k + 1) * 2 
LIMIT 10
    ```
    ```
    Before: SELECT `k` + 1,COUNT(*) FROM `db`.`t` GROUP BY `k` + 1 ORDER BY 
(`k` + 1) * 2 ASC LIMIT 10  -> MySQL error 1055
    Target: SELECT `k` + 1,COUNT(*) FROM `db`.`t` GROUP BY `k` + 1  (ORDER BY 
... LIMIT runs in Spark)
    ```
    
    ### Does this PR introduce _any_ user-facing change?
    Yes. Such queries now succeed instead of failing with 
`JDBC_EXTERNAL_ENGINE_SYNTAX_ERROR`; sort keys MySQL accepts (e.g. `ORDER BY k 
+ 1`, `ORDER BY COUNT(*)`) are still pushed.
    
    ### How was this patch tested?
    New tests in `MySQLIntegrationSuite`.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    Generated-by: Claude Code (Isaac) with Claude Opus 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #60235 from aleksandar-trajkovic-db/mysql-topn-after-aggregate.
    
    Authored-by: aleksandar-trajkovic-db <[email protected]>
    Signed-off-by: Uros Bojanic <[email protected]>
    (cherry picked from commit 3644a7b4082b5e356a67a1d62dbb1718d8a8be88)
    Signed-off-by: Uros Bojanic <[email protected]>
---
 .../spark/sql/jdbc/v2/MySQLIntegrationSuite.scala  | 69 +++++++++++++++++++++-
 .../org/apache/spark/sql/internal/SQLConf.scala    | 14 +++++
 .../datasources/v2/jdbc/JDBCScanBuilder.scala      |  4 ++
 .../org/apache/spark/sql/jdbc/JdbcDialects.scala   | 13 +++-
 .../org/apache/spark/sql/jdbc/MySQLDialect.scala   | 34 ++++++++++-
 5 files changed, 129 insertions(+), 5 deletions(-)

diff --git 
a/connector/docker-integration-tests/src/test/scala/org/apache/spark/sql/jdbc/v2/MySQLIntegrationSuite.scala
 
b/connector/docker-integration-tests/src/test/scala/org/apache/spark/sql/jdbc/v2/MySQLIntegrationSuite.scala
index b18e9e4dac82..138381026860 100644
--- 
a/connector/docker-integration-tests/src/test/scala/org/apache/spark/sql/jdbc/v2/MySQLIntegrationSuite.scala
+++ 
b/connector/docker-integration-tests/src/test/scala/org/apache/spark/sql/jdbc/v2/MySQLIntegrationSuite.scala
@@ -17,11 +17,12 @@
 
 package org.apache.spark.sql.jdbc.v2
 
-import java.sql.{Connection, SQLFeatureNotSupportedException}
+import java.sql.{Connection, Date, SQLFeatureNotSupportedException}
 
-import org.apache.spark.{SparkConf, SparkSQLFeatureNotSupportedException}
+import org.apache.spark.{SparkConf, SparkException, 
SparkSQLFeatureNotSupportedException}
 import org.apache.spark.sql.{AnalysisException, Row}
 import org.apache.spark.sql.execution.datasources.v2.jdbc.JDBCTableCatalog
+import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.jdbc.MySQLDatabaseOnDocker
 import org.apache.spark.sql.types._
 import org.apache.spark.tags.DockerTest
@@ -323,6 +324,70 @@ class MySQLIntegrationSuite extends 
DockerJDBCIntegrationV2Suite with V2JDBCTest
     checkFilterPushed(df, pushed = false)
     checkAnswer(df, Seq(Row("alex"), Row("jen")))
   }
+
+  test("SPARK-61032: TopN over a pushed GROUP BY expression") {
+    val emp = s"$catalogName.employee"
+
+    // MySQL rejects these sort keys under ONLY_FULL_GROUP_BY.
+    val rejected = Seq(
+      s"SELECT dept + 1, COUNT(*) FROM $emp GROUP BY dept + 1 ORDER BY (dept + 
1) * 2 DESC LIMIT 2"
+        -> Seq(Row(7, 1L), Row(3, 2L)),
+      s"SELECT dept + 1, COUNT(*) FROM $emp GROUP BY dept + 1 ORDER BY dept + 
1 DESC NULLS FIRST " +
+        "LIMIT 2" -> Seq(Row(7, 1L), Row(3, 2L)),
+      s"SELECT dept + 1, COUNT(*) FROM $emp GROUP BY dept + 1 ORDER BY (dept + 
1) * 2 " +
+        "LIMIT 1 OFFSET 1" -> Seq(Row(3, 2L)),
+      // An alias shadowing the column expands into this form, e.g.
+      // SELECT date_add(date1, 1) AS date1 ... ORDER BY date_add(date1, 1).
+      s"SELECT date_add(date1, 1), COUNT(*) FROM $catalogName.datetime " +
+        "GROUP BY date_add(date1, 1) ORDER BY date_add(date_add(date1, 1), 1) 
DESC LIMIT 2"
+        -> Seq(Row(Date.valueOf("2022-05-20"), 1L), 
Row(Date.valueOf("2022-05-19"), 1L)))
+    val accepted = Seq(
+      s"SELECT dept + 1, COUNT(*) FROM $emp GROUP BY dept + 1 ORDER BY dept + 
1 LIMIT 2"
+        -> Seq(Row(2, 2L), Row(3, 2L)),
+      s"SELECT dept + 1, COUNT(*) FROM $emp GROUP BY dept + 1 ORDER BY dept + 
1 DESC LIMIT 2"
+        -> Seq(Row(7, 1L), Row(3, 2L)),
+      s"SELECT month(date1), COUNT(*) FROM $catalogName.datetime GROUP BY 
month(date1) " +
+        "ORDER BY month(date1) LIMIT 1" -> Seq(Row(1, 1L)),
+      s"SELECT dept + 1, COUNT(*) FROM $emp GROUP BY dept + 1 ORDER BY 
COUNT(*) ASC NULLS LAST " +
+        "LIMIT 1" -> Seq(Row(7, 1L)),
+      s"SELECT dept, COUNT(*) FROM $emp GROUP BY dept ORDER BY dept * 2 DESC 
NULLS FIRST LIMIT 2"
+        -> Seq(Row(6, 1L), Row(2, 2L)),
+      s"SELECT dept FROM $emp ORDER BY dept * 2 DESC NULLS FIRST LIMIT 2" -> 
Seq(Row(6), Row(2)))
+
+    Seq(false, true).foreach { legacy =>
+      // Arithmetic is pushed only in ANSI mode.
+      withSQLConf(
+          SQLConf.ANSI_ENABLED.key -> "true",
+          SQLConf.LEGACY_MYSQL_TOP_N_OVER_GROUP_BY_EXPR_ENABLED.key -> 
legacy.toString) {
+        rejected.foreach { case (query, expected) =>
+          val df = sql(query)
+          checkAggregateRemoved(df)
+          if (legacy) {
+            // Legacy mode pushes the sort, so MySQL rejects it.
+            checkSortRemoved(df)
+            checkError(
+              exception = intercept[SparkException](df.collect()),
+              condition = 
"JDBC_EXTERNAL_ENGINE_SYNTAX_ERROR.DURING_QUERY_EXECUTION",
+              sqlState = Some("42000"),
+              parameters = Map(
+                "jdbcQuery" -> ".*ORDER BY.*",
+                "externalEngineSqlState" -> "42000",
+                "externalEngineError" -> "(?is).*only_full_group_by.*"),
+              matchPVals = true)
+          } else {
+            checkSortRemoved(df, pushed = false)
+            checkAnswer(df, expected)
+          }
+        }
+        accepted.foreach { case (query, expected) =>
+          val df = sql(query)
+          checkAggregateRemoved(df)
+          checkSortRemoved(df)
+          checkAnswer(df, expected)
+        }
+      }
+    }
+  }
 }
 
 /**
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
index 2b338e8a2ca5..e55c87676517 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
@@ -7416,6 +7416,17 @@ object SQLConf {
       .booleanConf
       .createWithDefault(false)
 
+  val LEGACY_MYSQL_TOP_N_OVER_GROUP_BY_EXPR_ENABLED =
+    buildConf("spark.sql.legacy.mysql.topNOverGroupByExpr.enabled")
+      .internal()
+      .doc("When true, push ORDER BY ... LIMIT to MySQL on top of a pushed 
GROUP BY even when " +
+        "a sort key is built over a GROUP BY expression, such as GROUP BY a + 
1 ORDER BY " +
+        "(a + 1) * 2. MySQL rejects such queries under the default 
ONLY_FULL_GROUP_BY mode.")
+      .version("4.4.0")
+      .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+      .booleanConf
+      .createWithDefault(false)
+
   val LEGACY_ORACLE_TIMESTAMP_MAPPING_ENABLED =
     buildConf("spark.sql.legacy.oracle.timestampMapping.enabled")
       .internal()
@@ -9815,6 +9826,9 @@ class SQLConf extends Serializable with Logging with 
SqlApiConf {
   def legacyMySqlTimestampNTZMappingEnabled: Boolean =
     getConf(LEGACY_MYSQL_TIMESTAMPNTZ_MAPPING_ENABLED)
 
+  def legacyMySqlTopNOverGroupByExprEnabled: Boolean =
+    getConf(LEGACY_MYSQL_TOP_N_OVER_GROUP_BY_EXPR_ENABLED)
+
   def legacyOracleTimestampMappingEnabled: Boolean =
     getConf(LEGACY_ORACLE_TIMESTAMP_MAPPING_ENABLED)
 
diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/jdbc/JDBCScanBuilder.scala
 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/jdbc/JDBCScanBuilder.scala
index 18a952677ef3..3d215ab946ce 100644
--- 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/jdbc/JDBCScanBuilder.scala
+++ 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/jdbc/JDBCScanBuilder.scala
@@ -98,6 +98,8 @@ case class JDBCScanBuilder(
 
   private var pushedGroupBys: Option[Array[String]] = None
 
+  private var pushedAggregation: Option[Aggregation] = None
+
   override def supportCompletePushDown(aggregation: Aggregation): Boolean = {
     lazy val fieldNames = aggregation.groupByExpressions()(0) match {
       case field: FieldReference => field.fieldNames
@@ -139,6 +141,7 @@ case class JDBCScanBuilder(
       finalSchema = JDBCRDD.getQueryOutputSchema(aggQuery, jdbcOptions, 
dialect)
       pushedAggregateList = selectList
       pushedGroupBys = Some(compiledGroupBys)
+      pushedAggregation = Some(aggregation)
       true
     } catch {
       case NonFatal(e) =>
@@ -341,6 +344,7 @@ case class JDBCScanBuilder(
   override def pushTopN(orders: Array[SortOrder], limit: Int): Boolean = {
     if (jdbcOptions.pushDownLimit) {
       if (orders.exists(containsUnsupportedCharPad)) return false
+      if (!dialect.supportsTopN(orders, pushedAggregation)) return false
       val compiledOrders = orders.flatMap(dialect.compileExpression(_))
       if (orders.length != compiledOrders.length) return false
       pushedLimit = limit
diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/jdbc/JdbcDialects.scala 
b/sql/core/src/main/scala/org/apache/spark/sql/jdbc/JdbcDialects.scala
index 17cf7009d5e1..091b8e2e5987 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/jdbc/JdbcDialects.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/jdbc/JdbcDialects.scala
@@ -43,8 +43,8 @@ import org.apache.spark.sql.connector.catalog.TableChange._
 import org.apache.spark.sql.connector.catalog.functions.UnboundFunction
 import org.apache.spark.sql.connector.catalog.index.TableIndex
 import org.apache.spark.sql.connector.expressions.{Expression, 
GeneralScalarExpression, Literal,
-  NamedReference}
-import org.apache.spark.sql.connector.expressions.aggregate.AggregateFunc
+  NamedReference, SortOrder}
+import org.apache.spark.sql.connector.expressions.aggregate.{AggregateFunc, 
Aggregation}
 import org.apache.spark.sql.connector.expressions.filter.{AlwaysFalse, 
AlwaysTrue, Predicate}
 import org.apache.spark.sql.connector.util.V2ExpressionSQLBuilder
 import org.apache.spark.sql.errors.QueryCompilationErrors
@@ -953,6 +953,15 @@ abstract class JdbcDialect extends Serializable with 
Logging {
    */
   def supportsJoin: Boolean = false
 
+  /**
+   * Returns false if the dialect cannot run the given ORDER BY ... LIMIT (top 
N) when pushed.
+   * `aggregation` is the aggregate already pushed into the same query, if 
any; it stays pushed
+   * either way. Returning true does not guarantee the push, as other pushdown 
checks still apply.
+   * Defaults to true.
+   */
+  @Since("4.4.0")
+  def supportsTopN(orders: Array[SortOrder], aggregation: 
Option[Aggregation]): Boolean = true
+
   /**
    * Return the DB-specific quoted and fully qualified table name
    */
diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/jdbc/MySQLDialect.scala 
b/sql/core/src/main/scala/org/apache/spark/sql/jdbc/MySQLDialect.scala
index 6878ea58e3ab..053ddf1c5ed8 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/jdbc/MySQLDialect.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/jdbc/MySQLDialect.scala
@@ -29,7 +29,8 @@ import org.apache.spark.sql.catalyst.SQLConfHelper
 import org.apache.spark.sql.catalyst.analysis.{IndexAlreadyExistsException, 
NoSuchIndexException}
 import org.apache.spark.sql.connector.catalog.Identifier
 import org.apache.spark.sql.connector.catalog.index.TableIndex
-import org.apache.spark.sql.connector.expressions.{Expression, Extract, 
FieldReference, NamedReference, NullOrdering, SortDirection}
+import org.apache.spark.sql.connector.expressions.{Expression, Extract, 
FieldReference, NamedReference, NullOrdering, SortDirection, SortOrder}
+import org.apache.spark.sql.connector.expressions.aggregate.{AggregateFunc, 
Aggregation}
 import org.apache.spark.sql.errors.{QueryCompilationErrors, 
QueryExecutionErrors}
 import org.apache.spark.sql.execution.datasources.jdbc.{JDBCOptions, JdbcUtils}
 import org.apache.spark.sql.types._
@@ -448,4 +449,35 @@ private case class MySQLDialect() extends JdbcDialect with 
SQLConfHelper with No
   override def supportsHint: Boolean = true
 
   override def supportsJoin: Boolean = true
+
+  // ONLY_FULL_GROUP_BY (on by default) rejects an ORDER BY term that uses a 
column outside an
+  // aggregate, unless that column is itself grouped or the term equals a 
GROUP BY expression.
+  override def supportsTopN(
+      orders: Array[SortOrder],
+      aggregation: Option[Aggregation]): Boolean = {
+    conf.legacyMySqlTopNOverGroupByExprEnabled || aggregation.forall { agg =>
+      val groupBys = agg.groupByExpressions.toSeq
+      // Compare compiled SQL: some V2 expressions, such as Extract, have no 
value equality.
+      val groupBySqls = groupBys.flatMap(compileExpression).toSet
+      orders.forall { order =>
+        equalsGroupByTerm(order, groupBySqls) ||
+          columnsOutsideAggregates(order.expression).forall(groupBys.contains)
+      }
+    }
+  }
+
+  // Other null orders compile to `CASE WHEN key IS NULL ...`, which differs 
from the GROUP BY term.
+  private def equalsGroupByTerm(order: SortOrder, groupBySqls: Set[String]): 
Boolean =
+    compileExpression(order.expression).exists(groupBySqls.contains) &&
+      ((order.direction, order.nullOrdering) match {
+        case (SortDirection.ASCENDING, NullOrdering.NULLS_FIRST) |
+             (SortDirection.DESCENDING, NullOrdering.NULLS_LAST) => true
+        case _ => false
+      })
+
+  private def columnsOutsideAggregates(e: Expression): Seq[Expression] = e 
match {
+    case _: AggregateFunc => Nil
+    case r: NamedReference => Seq(r)
+    case _ => e.children.toSeq.flatMap(columnsOutsideAggregates)
+  }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to