spark-test commented on code in PR #59962:
URL: https://github.com/apache/spark/pull/59962#discussion_r4520389455


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JdbcUtils.scala:
##########
@@ -722,75 +772,89 @@ object JdbcUtils extends Logging with SQLConfHelper {
     }
     val supportsTransactions = finalIsolationLevel != 
Connection.TRANSACTION_NONE
     var totalRowCount = 0L
+    def sourceHasNext: Boolean = {
+      try {
+        iterator.hasNext
+      } catch {
+        case e: SQLException =>
+          linkNextException(e)
+          throw e
+      }
+    }
+
+    def sourceNext(): Row = {
+      try {
+        iterator.next()
+      } catch {
+        case e: SQLException =>
+          linkNextException(e)
+          throw e
+      }
+    }
+
     try {
-      if (supportsTransactions) {
-        conn.setAutoCommit(false) // Everything in the same db transaction.
-        conn.setTransactionIsolation(finalIsolationLevel)
+      withWriteException {
+        if (supportsTransactions) {
+          conn.setAutoCommit(false) // Everything in the same db transaction.
+          conn.setTransactionIsolation(finalIsolationLevel)
+        }
       }
-      val stmt = conn.prepareStatement(insertStmt)
-      val setters =
+      val stmt = withWriteException { conn.prepareStatement(insertStmt) }
+      val setters = withWriteException {
         rddSchema.fields.map(f => makeSetter(conn, dialect, f.dataType, 
options))
-      val nullTypes = rddSchema.fields.map(f => getJdbcType(f.dataType, 
dialect).jdbcNullType)
+      }
+      val nullTypes = withWriteException {
+        rddSchema.fields.map(f => getJdbcType(f.dataType, 
dialect).jdbcNullType)
+      }
       val numFields = rddSchema.fields.length
 
       try {
         var rowCount = 0
 
-        stmt.setQueryTimeout(options.queryTimeout)
+        withWriteException { stmt.setQueryTimeout(options.queryTimeout) }
 
-        while (iterator.hasNext) {
-          val row = iterator.next()
-          var i = 0
-          while (i < numFields) {
-            if (row.isNullAt(i)) {
-              stmt.setNull(i + 1, nullTypes(i))
-            } else {
-              setters(i).apply(stmt, row, i)
+        while (sourceHasNext) {
+          val row = sourceNext()
+          try {
+            var i = 0
+            while (i < numFields) {
+              if (row.isNullAt(i)) {
+                stmt.setNull(i + 1, nullTypes(i))
+              } else {
+                setters(i).apply(stmt, row, i)
+              }
+              i = i + 1
             }
-            i = i + 1
+            stmt.addBatch()
+          } catch {
+            case e: SQLException => classifyWriteException(e)
           }
-          stmt.addBatch()
           rowCount += 1
           totalRowCount += 1
           if (rowCount % batchSize == 0) {
             // Hot spot for native blocking reads; TaskInterruptListener 
(registered after
             // opening the connection in this method) closes conn to unblock. 
JDBC 4.0 section 9.6:
             // methods on a closed Connection throw SQLException (expected for 
major drivers).
             // Mid-batch kill may drop the in-flight batch; still better than 
hanging forever.
-            stmt.executeBatch()
+            withWriteException { stmt.executeBatch() }
             rowCount = 0
           }
         }
         if (rowCount > 0) {
-          stmt.executeBatch()
+          withWriteException { stmt.executeBatch() }
         }
       } finally {
-        stmt.close()
+        // Cleanup must not replace a binding/batch failure or abort a pending 
commit.

Review Comment:
   **Non-blocking (P2):** This rule now covers `stmt.close()`, but the outer 
`finally` below still calls `conn.close()` unguarded on the failure path (line 
877), after a rollback whose failure is only logged. `Connection.close()` may 
throw `SQLException`, for example when a close-time rollback fails on a 
connection the failed batch left broken, and an exception thrown from a 
`finally` block discards the one in flight. Reading the code, a batch or commit 
failure followed by a failing close therefore leaves the task as the raw close 
error, which `abortStage` wraps in `Job aborted due to stage failure` with no 
condition, so neither `FAILED_JDBC.WRITE` nor the original cause survives. This 
applies to every write path and dialect, the migration note's list of 
unclassified cases (source iterator errors and task interruption) doesn't 
mention it, and no test makes `conn.close()` throw. Logging the failure-path 
close error, as the success path (line 885) and the statement cleanup here 
already
  do, keeps the classified failure; attaching it to the in-flight exception 
with `addSuppressed` would also work.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59962#pullrequestreview-5720099644).
   
   **Verification:**
   - **Regression:** For each destination failure that reaches the failure-path 
cleanup (transaction setup, statement preparation, query-timeout setup, row 
binding, batch execution and commit), a write whose connection close then 
throws a SQLException fails with FAILED_JDBC.WRITE, SQLSTATE HV000, the 
redacted URL and table, and that failure's original SQLException as its cause, 
after rollback, when the write is transactional, and close were both attempted.
   - **Behavior:** When a dialect maps the write failure to a specific 
condition, or the source iterator fails, and the connection close then throws, 
the write still fails with the mapped exception, or with the original source 
SQLException and its linked next exception.
   - **Compatibility:** An interrupted write still fails with the raw 
SQLException from the connection closed by the interrupt listener, and a write 
whose batches succeed still commits and reports success when a later close 
fails.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JdbcUtils.scala:
##########
@@ -670,7 +670,57 @@ object JdbcUtils extends Logging with SQLConfHelper {
 
     val outMetrics = TaskContext.get().taskMetrics().outputMetrics
 
-    val conn = dialect.createConnectionFactory(options)(-1)
+    def linkNextException(e: SQLException): Unit = {
+      val cause = e.getNextException
+      if (cause != null && e.getCause != cause) {
+        // If there is no cause already, set 'next exception' as cause. If 
cause is null,
+        // it *may* be because no cause was set yet
+        if (e.getCause == null) {
+          try {
+            e.initCause(cause)
+          } catch {
+            // Or it may be null because the cause *was* explicitly 
initialized, to *null*,
+            // in which case this fails. There is no other way to detect it.
+            // addSuppressed in this case as well.
+            case _: IllegalStateException => e.addSuppressed(cause)
+          }
+        } else {
+          e.addSuppressed(cause)
+        }
+      }
+    }
+
+    def classifyWriteException(e: SQLException): Nothing = {
+      linkNextException(e)
+      // Closing the connection on task cancellation can cause a SQLException. 
Do not
+      // report that cancellation side effect as a JDBC write failure.
+      if (TaskContext.get().isInterrupted() || e.isInstanceOf[SparkThrowable]) 
{
+        throw e
+      }
+      val parameters = Map("url" -> options.getRedactUrl(), "tableName" -> 
table)
+      val classified = dialect.classifyException(
+        e,
+        condition = "FAILED_JDBC.WRITE",
+        messageParameters = parameters,
+        description = s"Write rows to the table $table.",
+        isRuntime = true)
+      // The legacy classifier ignores the supplied condition and uses a 
placeholder URL.
+      // Normalize only its generic fallback so specific dialect mappings 
still take precedence.
+      if (classified.getCondition == "FAILED_JDBC.UNCLASSIFIED") {
+        throw new SparkRuntimeException("FAILED_JDBC.WRITE", parameters, e)
+      }
+      throw classified
+    }
+
+    def withWriteException[T](f: => T): T = {

Review Comment:
   **Nit (P3):** This helper covers only the executor partition write. The 
setup that runs on the Spark driver before it, the connection and table setup 
in `JdbcRelationProvider.createRelation` (existence check, truncate, drop, 
create) and the truncate in `JDBCWriteBuilder`, still throws raw 
`SQLException`s. The PR description and the migration note say that's deferred 
on purpose, but nothing at those call sites says so, so a maintainer reading 
them can't tell the deferral from an oversight, and a later change may classify 
them differently from the executor side. A TODO at those two call sites naming 
the deferred classification would make the boundary visible in the code.
   
   **Verification:**
   - **Inspection:** The driver-side connection acquisition and table setup in 
the V1 JDBC relation provider, and the truncate in the DSv2 JDBC write builder, 
each carry a TODO naming the deferred error classification, and no code 
behavior changes.



##########
sql/core/src/test/scala/org/apache/spark/sql/jdbc/JDBCWriteSuite.scala:
##########
@@ -570,10 +570,20 @@ class JDBCWriteSuite extends SharedSparkSession with 
BeforeAndAfter {
   }
 
   test("SPARK-19726: INSERT null to a NOT NULL column") {
-    val e = intercept[SparkException] {
-      sql("INSERT INTO PEOPLE1 values (null, null)")
-    }.getMessage
-    assert(e.contains("NULL not allowed for column \"NAME\""))
+    val e = intercept[SparkRuntimeException] {

Review Comment:
   **Nit (P3):** This test now expects the classified `SparkRuntimeException`, 
but the ignored `SPARK-23856 Spark jdbc setQueryTimeout option` test just below 
(lines 589-605) still wraps its write in `intercept[SparkException]` and looks 
for `Statement was canceled or the session timed out` in the top-level message. 
With `batchsize` set to `Int.MaxValue`, its timeout would come from the 
trailing `executeBatch`, which is now classified, so the job would fail with 
`FAILED_JDBC.WRITE` and carry the JDBC driver's text only on its cause. 
Re-enabling it would then fail on the exception type instead of checking the 
timeout. Updating it the same way as this test (intercept 
`SparkRuntimeException`, check `FAILED_JDBC.WRITE`, read the timeout text from 
the cause) and keeping it ignored would fix that.
   
   **Verification:**
   - **Inspection:** The ignored queryTimeout write test intercepts the 
classified write exception, checks FAILED_JDBC.WRITE, reads the driver's 
timeout message from the cause rather than the top-level message, and stays 
ignored.
   - **Compile:** The JDBC write test suite still compiles with the updated 
ignored test, which is the only executable signal for a test that does not run.



##########
docs/sql-migration-guide.md:
##########
@@ -29,6 +29,8 @@ license: |
 
 ## Upgrading from Spark SQL 4.3 to 4.4
 
+- Since Spark 4.4, `SQLException`s from destination JDBC calls during executor 
partition writes are classified through the JDBC dialect. This includes 
executor connection acquisition and write setup. Initial driver-side connection 
acquisition and table setup retain their existing error propagation. When a 
dialect has no more specific mapping, the failure is a `SparkRuntimeException` 
with condition `FAILED_JDBC.WRITE` and SQLSTATE `HV000`, rather than an 
unclassified `SQLException` inside a job-aborted `SparkException`. The write 
path also normalizes the default legacy classifier's generic 
`FAILED_JDBC.UNCLASSIFIED` result to this runtime condition. Dialect-specific 
mappings, including those in built-in dialects, can return other conditions. 
Spark Connect projects `FAILED_JDBC.WRITE` to `FAILED_JDBC.UNCLASSIFIED` so 
clients with older error catalogs can reconstruct it; other conditions are 
unchanged. Update handlers that catch `SparkException` or match the driver's 
text in the top-le
 vel message: use the public `SparkThrowable` interface to inspect the 
condition and SQLSTATE. The `FAILED_JDBC.WRITE` wrapper retains the original 
vendor message and SQLSTATE on its cause; its top-level `HV000` does not 
distinguish a constraint violation from a transient database failure. Source 
iterator errors and task interruption remain unclassified by the write path.

Review Comment:
   **Nit (P3):** Here "the driver's text" means the JDBC driver's 
`SQLException` message, which the next sentence calls "the original vendor 
message", but earlier in the same bullet "driver-side" means the Spark driver. 
A reader can take this advice to be about Spark driver output. Saying "match 
the JDBC driver's message text in the top-level message" avoids that.
   
   **Verification:**
   - **Inspection:** In the Spark 4.4 JDBC write note, each use of 'driver' 
makes clear whether it means the Spark driver or the JDBC driver, and the 
advice about handlers names the JDBC driver's or vendor's message.



-- 
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]

Reply via email to