Skip to content

BUG: Do not error on other dbapi2 connections #45679

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 4 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
9 changes: 6 additions & 3 deletions pandas/io/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -736,12 +736,15 @@ def pandasSQL_builder(con, schema: str | None = None):
if isinstance(con, sqlite3.Connection) or con is None:
return SQLiteDatabase(con)

sqlalchemy = import_optional_dependency("sqlalchemy")
sqlalchemy = import_optional_dependency("sqlalchemy", errors="ignore")

if isinstance(con, str):
con = sqlalchemy.create_engine(con)
if sqlalchemy is None:
raise ImportError("Using URI string without sqlalchemy installed.")
else:
con = sqlalchemy.create_engine(con)

if isinstance(con, sqlalchemy.engine.Connectable):
if sqlalchemy is not None and isinstance(con, sqlalchemy.engine.Connectable):
return SQLDatabase(con, schema=schema)

warnings.warn(
Expand Down
18 changes: 17 additions & 1 deletion pandas/tests/io/test_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -1524,9 +1524,25 @@ def test_sql_open_close(self, test_frame3):
@pytest.mark.skipif(SQLALCHEMY_INSTALLED, reason="SQLAlchemy is installed")
def test_con_string_import_error(self):
conn = "mysql://root@localhost/pandas"
with pytest.raises(ImportError, match="SQLAlchemy"):
msg = "Using URI string without sqlalchemy installed"
with pytest.raises(ImportError, match=msg):
sql.read_sql("SELECT * FROM iris", conn)

@pytest.mark.skipif(SQLALCHEMY_INSTALLED, reason="SQLAlchemy is installed")
def test_con_unknown_dbapi2_class_does_not_error_without_sql_alchemy_installed(
self,
):
class MockSqliteConnection:
def __init__(self, *args, **kwargs):
self.conn = sqlite3.Connection(*args, **kwargs)

def __getattr__(self, name):
return getattr(self.conn, name)

conn = MockSqliteConnection(":memory:")
with tm.assert_produces_warning(UserWarning):
sql.read_sql("SELECT 1", conn)

def test_read_sql_delegate(self):
iris_frame1 = sql.read_sql_query("SELECT * FROM iris", self.conn)
iris_frame2 = sql.read_sql("SELECT * FROM iris", self.conn)
Expand Down