Skip to content

Commit 03bfcc8

Browse files
committed
Enhance error handling in DBConnection and improve DBConnectionError message formatting
1 parent 8ce9c24 commit 03bfcc8

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

sqlcompare/db/connection.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,12 +196,22 @@ def _run(self, sql: str, params: dict[str, Any] | None = None) -> Result:
196196
res = self.conn.execute(text(sql), params or {})
197197
return res
198198
except SQLAlchemyError as e:
199+
# Extract just the database error message without the full SQL statement
200+
error_msg = str(e)
201+
# SQLAlchemy often includes the SQL in square brackets at the end
202+
# Format: "error message [SQL: long query here]"
203+
if "[SQL:" in error_msg:
204+
# Extract just the part before [SQL:
205+
db_error = error_msg.split("[SQL:")[0].strip()
206+
else:
207+
db_error = error_msg
208+
199209
raise DBConnectionError(
200-
"SQL execution failed.",
210+
db_error,
201211
conn_id=self.conn_id,
202212
sql=sql,
203213
original=e,
204-
) from e
214+
) from None # Suppress the original exception chain to avoid showing SQL twice
205215
finally:
206216
self.last_elapsed_ms = int((time.perf_counter() - t0) * 1000)
207217

sqlcompare/db/exceptions.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,17 @@ def __init__(
1111
self.conn_id = conn_id
1212
self.sql = sql
1313
self.original = original
14+
15+
def __str__(self) -> str:
16+
# The main error message is already set in __init__, just add SQL context if helpful
17+
msg = super().__str__()
18+
19+
# Optionally show a brief SQL snippet for context
20+
if self.sql and len(self.sql) > 200:
21+
# Only show snippet if SQL is long (short SQL is fine to show in full)
22+
sql_lines = self.sql.strip().split('\n')
23+
first_line = sql_lines[0] if sql_lines else self.sql
24+
sql_snippet = first_line[:100] + "..." if len(first_line) > 100 else first_line
25+
msg += f"\n\nSQL operation: {sql_snippet}"
26+
27+
return msg

0 commit comments

Comments
 (0)