Repository navigation
fix(sqlalchemy-spanner): close temporary reflection connections - #19241
Conversation
When a SQLAlchemy Engine was passed directly to a dialect introspection method (such as checking whether a table exists or inspecting columns and views), the dialect checked out a temporary connection from the pool without closing it afterward. If an exception occurred, active stack frames could keep that connection pinned and exhaust the connection pool; normal returns also bypassed explicit connection cleanup. Ensure any temporary connection opened for an Engine-based reflection call is always closed when the method returns or raises an error, while leaving caller-owned connections open and preserving wrapped method metadata.
There was a problem hiding this comment.
Code Review
This pull request updates the engine_to_connection decorator in sqlalchemy_spanner.py to ensure that any temporary connections opened from an Engine are properly closed using a try...finally block, preventing connection leaks. It also applies @functools.wraps to preserve the wrapped function's metadata. Comprehensive unit and mock server tests have been added to verify connection closure on success and exception, nested call handling, and metadata preservation. There are no review comments, so I have no feedback to provide.
|
@olavloite , Please could you resolve the file conficts? |
| mock_engine.connect.assert_called_once_with() | ||
| mock_connection.close.assert_called_once_with() | ||
|
|
||
| def test_engine_to_connection_does_not_close_existing_connection(self): |
There was a problem hiding this comment.
Can we add one more negative test? (throws exception)
def test_engine_to_connection_does_not_close_existing_connection(self):
"""Test that engine_to_connection leaves caller-owned Connections open."""
dialect = SpannerDialect()
mock_connection = self._mock_connection_with_rows([])
assert dialect.has_table(mock_connection, "my_table") is False
mock_connection.close.assert_not_called()
with pytest.raises(NoSuchTableError, match=r"\.missing_view"):
dialect.get_view_definition(mock_connection, "missing_view")
mock_connection.close.assert_not_called()There was a problem hiding this comment.
Done (added to existing test)
When a SQLAlchemy Engine was passed directly to a dialect introspection method (such as checking whether a table exists or inspecting columns and views), the dialect checked out a temporary connection from the pool without closing it afterward. If an exception occurred, active stack frames could keep that connection pinned and exhaust the connection pool; normal returns also bypassed explicit connection cleanup.
Ensure any temporary connection opened for an Engine-based reflection call is always closed when the method returns or raises an error, while leaving caller-owned connections open and preserving wrapped method metadata.