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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix/improvement: add cursor introspection for dbapi spec (#5557)
Shahmir Varqhadb8242aa311c
diff --git a/frontend/src/components/datasources/datasources.tsx b/frontend/src/components/datasources/datasources.tsxindex 92a28a811e..283af913d2 100644--- a/frontend/src/components/datasources/datasources.tsx+++ b/frontend/src/components/datasources/datasources.tsx@@ -501,7 +501,7 @@ const DatasetTableItem: React.FC<{React.useState(false);const tableDetailsExist = table.columns.length > 0;- const { isPending, error } = useAsyncData(async () => {+ const { isFetching, isPending, error } = useAsyncData(async () => {if (isExpanded &&!tableDetailsExist &&@@ -585,7 +585,7 @@ const DatasetTableItem: React.FC<{};const renderColumns = () => {- if (isPending) {+ if (isPending || isFetching) {return <LoadingState message="Loading columns..." className="pl-12" />;}diff --git a/marimo/_sql/engines/dbapi.py b/marimo/_sql/engines/dbapi.pyindex 2e58b3eea4..a1467db8c5 100644--- a/marimo/_sql/engines/dbapi.py+++ b/marimo/_sql/engines/dbapi.py@@ -144,3 +144,98 @@ class DBAPIEngine(QueryEngine[DBAPIConnection]):except Exception:return False++ @staticmethod+ def is_dbapi_cursor(obj: Any) -> bool:+ """+ Return True if obj looks like a DB-API 2.0 cursor.+ """+ try:+ # Required methods+ has_execute = callable(getattr(obj, "execute", None))+ # has_executemany = callable(getattr(obj, "executemany", None))++ # At least one fetch method+ fetch_methods = ("fetchone", "fetchmany", "fetchall")+ has_fetch = any(+ callable(getattr(obj, m, None)) for m in fetch_methods+ )++ # Required attributes (description may be None after DML, but must exist)+ has_description_attr = hasattr(obj, "description")+ has_rowcount = hasattr(obj, "rowcount")++ return (+ has_execute+ and has_fetch+ and has_description_attr+ and has_rowcount+ )+ except Exception:+ return False++ @staticmethod+ def get_cursor_metadata(cursor: Any) -> dict[str, Any]:+ """+ Extract standard DB-API 2.0 cursor metadata.+ """+ try:+ meta: dict[str, Any] = {+ "result_type": f"{type(cursor)}",+ }++ # Column info+ desc = getattr(cursor, "description", None)+ if desc:+ cols: list[dict[str, Optional[Any]]] = []+ for col in desc:+ # description tuple: (name, type_code, display_size, internal_size, precision, scale, null_ok)+ name = col[0]+ type_code = col[1] if len(col) > 1 else None+ display_size = col[2] if len(col) > 2 else None+ internal_size = col[3] if len(col) > 3 else None+ precision = col[4] if len(col) > 4 else None+ scale = col[5] if len(col) > 5 else None+ null_ok = col[6] if len(col) > 6 else None++ cols.append(+ {+ "name": name,+ "type_code": type_code,+ "display_size": display_size,+ "internal_size": internal_size,+ "precision": precision,+ "scale": scale,+ "null_ok": null_ok,+ }+ )+ meta["columns"] = cols+ else:+ meta["columns"] = None++ if hasattr(cursor, "rowcount"):+ meta["rowcount"] = cursor.rowcount++ # lastrowid (optional in many drivers)+ if hasattr(cursor, "lastrowid"):+ meta["lastrowid"] = cursor.lastrowid++ # SQL type guess+ # rowcount == -1 usually means SELECT (or DDL), >=0 means DML or SELECT (after execute)+ rc = getattr(cursor, "rowcount", None)+ if rc is None:+ sql_type = "Unknown"+ elif rc == -1:+ sql_type = "Query/DDL"+ else:+ sql_type = "Query/DML"+ meta["sql_statement_type"] = sql_type++ return meta++ except Exception:+ LOGGER.warning("Failed to extract cursor metadata", exc_info=True)+ return {+ "result_type": f"{type(cursor)}",+ "error": "Failed to extract metadata",+ }diff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.pyindex ee83925e41..8cb97a84fc 100644--- a/marimo/_sql/sql.py+++ b/marimo/_sql/sql.py@@ -7,7 +7,7 @@ from typing import Any, Literal, Optional, castfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._output.rich_help import mddocfrom marimo._runtime.output import replace-from marimo._sql.engines.dbapi import DBAPIConnection+from marimo._sql.engines.dbapi import DBAPIConnection, DBAPIEnginefrom marimo._sql.engines.duckdb import DuckDBEnginefrom marimo._sql.engines.sqlalchemy import SQLAlchemyEnginefrom marimo._sql.engines.types import QueryEngine@@ -118,6 +118,10 @@ def sql(result = SQLAlchemyEngine.get_cursor_metadata(df)if result is not None:display_df = result+ elif DBAPIEngine.is_dbapi_cursor(df):+ result = DBAPIEngine.get_cursor_metadata(df)+ if result is not None:+ display_df = resultt = table.table(display_df,diff --git a/tests/_sql/test_dbapi.py b/tests/_sql/test_dbapi.pyindex f2f37e4095..b9d1b07b4e 100644--- a/tests/_sql/test_dbapi.py+++ b/tests/_sql/test_dbapi.py@@ -143,3 +143,24 @@ def test_execute_with_parameters(dbapi_engine: DBAPIEngine) -> None:)assert len(result) == 1assert result.iloc[0].to_dict() == {"id": 1, "name": "a", "value": 1.0}+++def test_is_dbapi_cursor() -> None:+ cursor = sqlite3.connect(":memory:").cursor()+ assert DBAPIEngine.is_dbapi_cursor(cursor)++ # Test with non-DBAPI object+ assert not DBAPIEngine.is_dbapi_cursor("not a cursor")+ assert not DBAPIEngine.is_dbapi_cursor(None)+++def test_get_cursor_metadata(dbapi_engine: DBAPIEngine) -> None:+ with patch.object(+ dbapi_engine, "sql_output_format", return_value="native"+ ):+ result = dbapi_engine.execute("SELECT * FROM test")+ result = DBAPIEngine.get_cursor_metadata(result)++ assert result is not None+ assert len(result["columns"]) == 3+ assert result["sql_statement_type"] == "Query/DDL"