Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 33 additions & 5 deletions jaydebeapiarrow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,24 @@ def reraise(tp, value, tb=None):

old_jpype = False

def _build_java_exception_message(exc):
"""Build a clean, informative error message from a Java exception.

Extracts the exception class name, message, and walks the cause chain
so that wrapped exceptions (e.g. RuntimeException wrapping an IOException)
are visible to the user. This avoids the duplicated class-name artefact
that JPype 1.7.0+ produces via ``str(exc)``.
"""
parts = []
current = exc
while current is not None:
cls_name = current.getClass().getName()
msg = str(current.getMessage()) if current.getMessage() else ""
parts.append(f"{cls_name}: {msg}" if msg else cls_name)
current = current.getCause()
return "\n Caused by: ".join(parts)


def _handle_sql_exception_jpype():
import jpype
SQLException = jpype.java.sql.SQLException
Expand All @@ -125,8 +143,9 @@ def _handle_sql_exception_jpype():
exc_type = DatabaseError
else:
exc_type = InterfaceError

reraise(exc_type, exc_info[1], exc_info[2])

message = _build_java_exception_message(exc_info[1])
reraise(exc_type, message, exc_info[2])

def _jdbc_connect_jpype(jclassname, url, driver_args, jars, libs):
import jpype
Expand Down Expand Up @@ -621,7 +640,10 @@ def execute(self, operation, parameters=None):
parameters = ()
self._close_last()
self.lastrowid = None
self._prep = self._connection.jconn.prepareStatement(operation)
try:
self._prep = self._connection.jconn.prepareStatement(operation)
except:
_handle_sql_exception()
self._set_stmt_parms(self._prep, parameters, is_batch=False)
try:
is_rs = self._prep.execute()
Expand All @@ -638,9 +660,15 @@ def execute(self, operation, parameters=None):
def executemany(self, operation, seq_of_parameters):
self._close_last()
self.lastrowid = None
self._prep = self._connection.jconn.prepareStatement(operation)
try:
self._prep = self._connection.jconn.prepareStatement(operation)
except:
_handle_sql_exception()
self._set_stmt_parms(self._prep, seq_of_parameters, is_batch=True)
update_counts = self._prep.executeBatch()
try:
update_counts = self._prep.executeBatch()
except:
_handle_sql_exception()
# self._prep.getWarnings() ???
self.rowcount = sum(update_counts)
self._close_last()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,22 @@ public final void mockBinaryResult(byte[] value) throws SQLException {
Mockito.when(this.prepareStatement(Mockito.any())).thenReturn(mockPreparedStatement);
}

public final void mockExceptionOnExecuteWithCause(String className, String message,
String causeClassName, String causeMessage) throws SQLException {
PreparedStatement mockPreparedStatement = Mockito.mock(PreparedStatement.class);
Throwable cause = createException(causeClassName, causeMessage);
Throwable exception;
try {
exception = (Throwable) Class.forName(className)
.getConstructor(String.class, Throwable.class)
.newInstance(message, cause);
} catch (Exception e) {
throw new RuntimeException("Couldn't initialize class " + className + " with cause.", e);
}
Mockito.when(mockPreparedStatement.execute()).thenThrow(exception);
Mockito.when(this.prepareStatement(Mockito.any())).thenReturn(mockPreparedStatement);
}

public final void mockBigDecimalResult(long value, int scale) throws SQLException {
PreparedStatement mockPreparedStatement = Mockito.mock(PreparedStatement.class);
Mockito.when(mockPreparedStatement.execute()).thenReturn(true);
Expand Down
Binary file not shown.
13 changes: 13 additions & 0 deletions test/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,19 @@ def test_lastrowid_none_after_executemany(self):
cursor.executemany(stmt, parms)
self.assertIsNone(cursor.lastrowid)

def test_sql_exception_message_is_clean(self):
"""SQL exceptions should produce clean messages without JPype artefacts."""
with self.conn.cursor() as cursor:
with self.assertRaises(jaydebeapiarrow.DatabaseError) as cm:
cursor.execute("SELECT * FROM nonexistent_table")
msg = str(cm.exception)
# Should contain a JDBC exception class name
self.assertTrue("Exception" in msg, f"Expected 'Exception' in: {msg}")
# Should not contain duplicated class names (JPype 1.7.0+ artefact)
self.assertNotIn("java.sql.java.sql", msg)
self.assertNotIn("com.microsoft.com.microsoft", msg)
self.assertNotIn("oracle.jdbc.oracle.jdbc", msg)

def test_execute_type_blob(self):
stmt = "insert into ACCOUNT (ACCOUNT_ID, ACCOUNT_NO, BALANCE, " \
"STUFF) values (?, ?, ?, ?)"
Expand Down
31 changes: 29 additions & 2 deletions test/test_mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,10 +517,37 @@ def test_runtime_exception_on_execute(self):
cursor.execute("dummy stmt")
self.fail("expected exception")
except jaydebeapiarrow.InterfaceError as e:
# JPype 1.4.1: "java.lang.RuntimeException: expected"
# JPype 1.7.0+: "java.lang.java.lang.RuntimeException: java.lang.RuntimeException: expected"
self.assertIn("RuntimeException: expected", str(e))

def test_runtime_exception_on_execute_includes_cause_chain(self):
"""RuntimeException with a nested cause should include the cause message."""
self.conn.jconn.mockExceptionOnExecuteWithCause(
"java.lang.RuntimeException",
"outer error",
"java.io.IOException",
"Connection reset by peer")
with self.conn.cursor() as cursor:
try:
cursor.execute("dummy stmt")
self.fail("expected exception")
except jaydebeapiarrow.InterfaceError as e:
msg = str(e)
self.assertIn("RuntimeException: outer error", msg)
self.assertIn("Connection reset by peer", msg)

def test_runtime_exception_on_execute_no_duplicate_classname(self):
"""Error message should not contain duplicated Java class names."""
self.conn.jconn.mockExceptionOnExecute("java.lang.RuntimeException", "expected")
with self.conn.cursor() as cursor:
try:
cursor.execute("dummy stmt")
self.fail("expected exception")
except jaydebeapiarrow.InterfaceError as e:
msg = str(e)
# Should NOT contain the JPype 1.7.0+ duplication like
# "java.lang.java.lang.RuntimeException"
self.assertNotIn("java.lang.java.lang", msg)

def test_sql_exception_on_commit(self):
self.conn.jconn.mockExceptionOnCommit("java.sql.SQLException", "expected")
try:
Expand Down
Loading
Loading