Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
24 changes: 16 additions & 8 deletions sqlmesh/utils/connection_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,12 +167,16 @@ def begin(self) -> None:
self._thread_transactions.add(get_ident())

def commit(self) -> None:
self._do_commit()
self._discard_transaction(get_ident())
try:
self._do_commit()
finally:
self._discard_transaction(get_ident())

def rollback(self) -> None:
self._do_rollback()
self._discard_transaction(get_ident())
try:
self._do_rollback()
finally:
self._discard_transaction(get_ident())

@property
def is_transaction_active(self) -> bool:
Expand Down Expand Up @@ -312,12 +316,16 @@ def begin(self) -> None:
self._is_transaction_active = True

def commit(self) -> None:
self._do_commit()
self._is_transaction_active = False
try:
self._do_commit()
finally:
self._is_transaction_active = False

def rollback(self) -> None:
self._do_rollback()
self._is_transaction_active = False
try:
self._do_rollback()
finally:
self._is_transaction_active = False

@property
def is_transaction_active(self) -> bool:
Expand Down
25 changes: 25 additions & 0 deletions tests/utils/test_connection_pool.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from concurrent.futures import ThreadPoolExecutor
from threading import get_ident

import pytest
from pytest_mock.plugin import MockerFixture

from sqlmesh.utils.connection_pool import (
Expand Down Expand Up @@ -323,3 +324,27 @@ def test_thread_local_shared_connection_pool_close(mocker: MockerFixture):
assert cursor_mock.close.call_count == 2
assert connection_factory_mock.call_count == 2
assert connection_mock.close.call_count == 2


@pytest.mark.parametrize(
"pool_class",
[SingletonConnectionPool, ThreadLocalConnectionPool, ThreadLocalSharedConnectionPool],
)
@pytest.mark.parametrize("method", ["commit", "rollback"])
def test_connection_pool_failed_commit_or_rollback_ends_transaction(
mocker: MockerFixture, pool_class, method: str
):
cursor_mock = mocker.Mock()
connection_mock = mocker.Mock()
connection_mock.cursor.return_value = cursor_mock
pool = pool_class(mocker.Mock(return_value=connection_mock))

pool.begin()
assert pool.is_transaction_active

getattr(cursor_mock, method).side_effect = RuntimeError("serializable isolation violation")
with pytest.raises(RuntimeError):
getattr(pool, method)()

# a later transaction must start with a BEGIN, not be taken for part of the failed one
assert not pool.is_transaction_active