Repository: ploomber/jupysql
Pull request #189 (2023-03-01 23:20:34)

Add: test - error when there is no active connection - 156 to master
Fix https://github.com/ploomber/jupysql/pull/171#issuecomment-1450947174
This should go to master


---------

## Describe your changes

## Issue ticket number and link
Closes #x

## Checklist before requesting a review

- [ ] I have performed a self-review of my code
- [ ] I have added thorough [tests](https://github.com/ploomber/contributing/blob/main/CONTRIBUTING.md#testing) (when necessary).
- [ ] I have added the right documentation in the [docstring](https://github.com/ploomber/contributing/blob/main/CONTRIBUTING.md#documenting-changes-and-new-features) and [changelog](https://github.com/ploomber/contributing/blob/main/CONTRIBUTING.md#changelog) (when needed)



<!-- readthedocs-preview jupysql start -->
----
:books: Documentation preview :books:: https://jupysql--189.org.readthedocs.build/en/189/

<!-- readthedocs-preview jupysql end -->


Patch:
diff --git a/src/sql/connection.py b/src/sql/connection.py
index e8c1304..313e53d 100644
--- a/src/sql/connection.py
+++ b/src/sql/connection.py
@@ -78,9 +78,7 @@ def get_missing_package_suggestion_str(e):
         module_name, MISSING_PACKAGE_LIST_EXCEPT_MATCHERS.keys()
     )
     if close_matches:
-        return "Perhaps you meant to use driver the dialect: \"{}\"".format(
-            close_matches[0]
-        )
+        return f"Perhaps you meant to use driver the dialect: \"{close_matches[0]}\""
     # Not found
     return (
         suggestion_prefix + "make sure you are using correct driver name:\n"
@@ -337,12 +335,13 @@ class Connection:
     def close(self):
         self.__class__._close(self)
 
-    def _get_curr_connection_info(self):
+    @classmethod
+    def _get_curr_connection_info(cls):
         """Returns the dialect, driver, and database server version info"""
-        if not self.current:
+        if not cls.current:
             return None
 
-        engine = self.current.metadata.bind
+        engine = cls.current.metadata.bind
         return {
             "dialect": getattr(engine.dialect, "name", None),
             "driver": getattr(engine.dialect, "driver", None),
diff --git a/src/sql/magic.py b/src/sql/magic.py
index 37085f5..9912350 100644
--- a/src/sql/magic.py
+++ b/src/sql/magic.py
@@ -116,7 +116,6 @@ class SqlMagic(Magics, Configurable):
 
     @telemetry.log_call("init")
     def __init__(self, shell):
-
         self._store = store
 
         Configurable.__init__(self, config=shell.config)
@@ -296,7 +295,9 @@ class SqlMagic(Magics, Configurable):
             creator=args.creator,
             alias=args.alias,
         )
-        payload["connection_info"] = conn._get_curr_connection_info()
+        payload[
+            "connection_info"
+        ] = sql.connection.Connection._get_curr_connection_info()
         if args.persist:
             return self._persist_dataframe(
                 command.sql, conn, user_ns, append=False, index=not args.no_index
@@ -344,7 +345,6 @@ class SqlMagic(Magics, Configurable):
 
                 return None
             else:
-
                 if command.result_var:
                     self.shell.user_ns.update({command.result_var: result})
                     return None
diff --git a/src/sql/plot.py b/src/sql/plot.py
index 9319370..f0de992 100644
--- a/src/sql/plot.py
+++ b/src/sql/plot.py
@@ -244,10 +244,9 @@ def boxplot(payload, table, column, *, orient="v", with_=None, conn=None):
     if not conn:
         conn = sql.connection.Connection.current.session
 
-    if sql.connection.Connection.current:
-        payload[
+    payload[
             "connection_info"
-        ] = sql.connection.Connection.current._get_curr_connection_info()
+        ] = sql.connection.Connection._get_curr_connection_info()
 
     ax = plt.gca()
     vert = orient == "v"
@@ -329,10 +328,9 @@ def histogram(payload, table, column, bins, with_=None, conn=None):
     .. plot:: ../examples/plot_histogram_many.py
     """
     ax = plt.gca()
-    if sql.connection.Connection.current:
-        payload[
+    payload[
             "connection_info"
-        ] = sql.connection.Connection.current._get_curr_connection_info()
+        ] = sql.connection.Connection._get_curr_connection_info()
     if isinstance(column, str):
         bin_, height = _histogram(table, column, bins, with_=with_, conn=conn)
         ax.bar(bin_, height, align="center", width=bin_[-1] - bin_[-2])
diff --git a/src/sql/run.py b/src/sql/run.py
index 518bc81..faa5f15 100644
--- a/src/sql/run.py
+++ b/src/sql/run.py
@@ -174,7 +174,7 @@ class ResultSet(list, ColumnGuesserMixin):
         frame = pd.DataFrame(self, columns=(self and self.keys) or [])
         payload[
             "connection_info"
-        ] = sql.connection.Connection.current._get_curr_connection_info()
+        ] = sql.connection.Connection._get_curr_connection_info()
         return frame
 
     @telemetry.log_call("polars-data-frame")


Test patch:
diff --git a/src/tests/test_connection.py b/src/tests/test_connection.py
index 4e0370d..982d890 100644
--- a/src/tests/test_connection.py
+++ b/src/tests/test_connection.py
@@ -37,8 +37,8 @@ def test_alias(cleanup):
 
 
 def test_get_curr_connection_info(mock_postgres):
-    conn = Connection.from_connect_str("postgresql://user:topsecret@somedomain.com/db")
-    assert conn._get_curr_connection_info() == {
+    Connection.from_connect_str("postgresql://user:topsecret@somedomain.com/db")
+    assert Connection._get_curr_connection_info() == {
         "dialect": "postgresql",
         "driver": "psycopg2",
         "server_version_info": None,
@@ -92,3 +92,8 @@ def test_missing_driver(
             Connection.from_connect_str(connect_str)
 
         assert "try to install package: " + missing_pkg in str(error.value)
+
+
+def test_no_current_connection_and_get_info(monkeypatch):
+    monkeypatch.setattr(Connection, "current", None)
+    assert Connection._get_curr_connection_info() is None