Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: catch sqlalchemy types (#6519)

Dylan Madisetti3414073ecf5e
diff --git a/marimo/_sql/error_utils.py b/marimo/_sql/error_utils.py
index 0c9510d4c7..4a5b46de2e 100644
--- a/marimo/_sql/error_utils.py
+++ b/marimo/_sql/error_utils.py
@@ -49,7 +49,7 @@ class SQLErrorMetadata(TypedDict):
def is_sql_parse_error(exception: BaseException) -> bool:
"""Check if the exception is a SQL parsing error."""
# Check for DuckDB exceptions first (most common)
- if DependencyManager.duckdb.has():
+ if DependencyManager.duckdb.imported():
try:
import duckdb
@@ -73,7 +73,7 @@ def is_sql_parse_error(exception: BaseException) -> bool:
pass
# Check for SQLGlot exceptions
- if DependencyManager.sqlglot.has():
+ if DependencyManager.sqlglot.imported():
try:
from sqlglot.errors import ParseError
@@ -84,6 +84,17 @@ def is_sql_parse_error(exception: BaseException) -> bool:
except ImportError:
pass
+ if DependencyManager.sqlalchemy.imported():
+ try:
+ from sqlalchemy.exc import ProgrammingError, SQLAlchemyError
+
+ # Definitions can be found here:
+ # https://docs.sqlalchemy.org/en/20/core/exceptions.html
+ if isinstance(exception, (SQLAlchemyError, ProgrammingError)):
+ return True
+ except ImportError:
+ pass
+
return isinstance(exception, MarimoSQLException)
diff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.py
index 0026efdccd..805a3b0115 100644
--- a/marimo/_sql/sql.py
+++ b/marimo/_sql/sql.py
@@ -109,13 +109,15 @@ def sql(
)
# Raise MarimoSQLException with structured hint data
+ # NB. raising _from_ creates a noisier stack trace, but preserves
+ # the original exception context for debugging.
raise MarimoSQLException(
message=clean_message,
sql_statement=truncated_query,
sql_line=metadata["sql_line"],
sql_col=metadata["sql_col"],
hint=metadata["hint"],
- ) from None
+ ) from e
raise
if df is None:
diff --git a/tests/_sql/test_sql.py b/tests/_sql/test_sql.py
index 83b7a24a57..3b60c683e5 100644
--- a/tests/_sql/test_sql.py
+++ b/tests/_sql/test_sql.py
@@ -142,11 +142,15 @@ def test_invalid_sql(
import duckdb
import sqlalchemy
- with pytest.raises(duckdb.Error):
+ from marimo._sql.error_utils import MarimoSQLException
+
+ with pytest.raises(MarimoSQLException) as exc_info:
sql("SELECT *", engine=duckdb_connection)
+ assert isinstance(exc_info.value.__cause__, duckdb.Error)
- with pytest.raises(sqlalchemy.exc.StatementError):
+ with pytest.raises(MarimoSQLException) as exc_info:
sql("SELECT *", engine=sqlite_engine)
+ assert isinstance(exc_info.value.__cause__, sqlalchemy.exc.StatementError)
# TODO