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
19 changes: 15 additions & 4 deletions asyncpg/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,12 +184,19 @@ async def __commit(self):
query = 'COMMIT;'

try:
await self._connection.execute(query)
result = await self._connection.execute(query)
except BaseException:
self._state = TransactionState.FAILED
raise
else:
self._state = TransactionState.COMMITTED

# An aborted transaction cannot be committed. PostgreSQL completes
# COMMIT with the command tag ROLLBACK and discards the changes.
if not self._nested and result == 'ROLLBACK':
self._state = TransactionState.ROLLEDBACK
raise apg_errors.InterfaceError(
'cannot commit; the server rolled the transaction back')

self._state = TransactionState.COMMITTED

async def __rollback(self):
self.__check_state('rollback')
Expand All @@ -212,7 +219,11 @@ async def __rollback(self):

@connresource.guarded
async def commit(self):
"""Exit the transaction or savepoint block and commit changes."""
"""Exit the transaction or savepoint block and commit changes.

Raises ``InterfaceError`` if the server answers ``COMMIT`` with
``ROLLBACK`` because an earlier statement failed.
"""
if self._managed:
raise apg_errors.InterfaceError(
'cannot manually commit from within an `async with` block')
Expand Down
12 changes: 7 additions & 5 deletions tests/test_prepare.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,11 +451,13 @@ async def check_simple():

# Try a cursor/timeout combination. Cursors should always use
# named prepared statements.
async with self.con.transaction():
with self.assertRaises(asyncio.TimeoutError):
async for _ in self.con.cursor( # NOQA
'select pg_sleep(10)', timeout=0.1):
pass
with self.assertRaisesRegex(
asyncpg.InterfaceError, 'rolled the transaction back'):
async with self.con.transaction():
with self.assertRaises(asyncio.TimeoutError):
async for _ in self.con.cursor( # NOQA
'select pg_sleep(10)', timeout=0.1):
pass

# Check that we can run queries after a failed cursor
# operation.
Expand Down
78 changes: 45 additions & 33 deletions tests/test_timeout.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,13 @@ async def test_timeout_04(self):
self.assertEqual(await self.con.fetch('select 1'), [(1,)])

st = await self.con.prepare('select pg_sleep(10)', timeout=0.1)
async with self.con.transaction():
cur = await st.cursor()
with self.assertRaises(asyncio.TimeoutError), \
self.assertRunUnder(MAX_RUNTIME):
await cur.fetch(1, timeout=0.1)
with self.assertRaisesRegex(
asyncpg.InterfaceError, 'rolled the transaction back'):
async with self.con.transaction():
cur = await st.cursor()
with self.assertRaises(asyncio.TimeoutError), \
self.assertRunUnder(MAX_RUNTIME):
await cur.fetch(1, timeout=0.1)
self.assertEqual(await self.con.fetch('select 1'), [(1,)])

async def test_timeout_05(self):
Expand All @@ -75,40 +77,50 @@ async def test_timeout_05(self):
self.assertEqual(await self.con.fetch('SELECT 1'), [(1,)])

async def test_timeout_06(self):
async with self.con.transaction():
with self.assertRaises(asyncio.TimeoutError), \
self.assertRunUnder(MAX_RUNTIME):
async for _ in self.con.cursor( # NOQA
'select pg_sleep(10)', timeout=0.1):
pass
with self.assertRaisesRegex(
asyncpg.InterfaceError, 'rolled the transaction back'):
async with self.con.transaction():
with self.assertRaises(asyncio.TimeoutError), \
self.assertRunUnder(MAX_RUNTIME):
async for _ in self.con.cursor( # NOQA
'select pg_sleep(10)', timeout=0.1):
pass
self.assertEqual(await self.con.fetch('select 1'), [(1,)])

async with self.con.transaction():
cur = await self.con.cursor('select pg_sleep(10)')
with self.assertRaises(asyncio.TimeoutError), \
self.assertRunUnder(MAX_RUNTIME):
await cur.fetch(1, timeout=0.1)
with self.assertRaisesRegex(
asyncpg.InterfaceError, 'rolled the transaction back'):
async with self.con.transaction():
cur = await self.con.cursor('select pg_sleep(10)')
with self.assertRaises(asyncio.TimeoutError), \
self.assertRunUnder(MAX_RUNTIME):
await cur.fetch(1, timeout=0.1)

async with self.con.transaction():
cur = await self.con.cursor('select pg_sleep(10)')
with self.assertRaises(asyncio.TimeoutError), \
self.assertRunUnder(MAX_RUNTIME):
await cur.forward(1, timeout=1e-10)
with self.assertRaisesRegex(
asyncpg.InterfaceError, 'rolled the transaction back'):
async with self.con.transaction():
cur = await self.con.cursor('select pg_sleep(10)')
with self.assertRaises(asyncio.TimeoutError), \
self.assertRunUnder(MAX_RUNTIME):
await cur.forward(1, timeout=1e-10)

async with self.con.transaction():
cur = await self.con.cursor('select pg_sleep(10)')
with self.assertRaises(asyncio.TimeoutError), \
self.assertRunUnder(MAX_RUNTIME):
await cur.fetchrow(timeout=0.1)
with self.assertRaisesRegex(
asyncpg.InterfaceError, 'rolled the transaction back'):
async with self.con.transaction():
cur = await self.con.cursor('select pg_sleep(10)')
with self.assertRaises(asyncio.TimeoutError), \
self.assertRunUnder(MAX_RUNTIME):
await cur.fetchrow(timeout=0.1)

async with self.con.transaction():
cur = await self.con.cursor('select pg_sleep(10)')
with self.assertRaises(asyncio.TimeoutError), \
self.assertRunUnder(MAX_RUNTIME):
await cur.fetchrow(timeout=0.1)
with self.assertRaisesRegex(
asyncpg.InterfaceError, 'rolled the transaction back'):
async with self.con.transaction():
cur = await self.con.cursor('select pg_sleep(10)')
with self.assertRaises(asyncio.TimeoutError), \
self.assertRunUnder(MAX_RUNTIME):
await cur.fetchrow(timeout=0.1)

with self.assertRaises(asyncpg.InFailedSQLTransactionError):
await cur.fetch(1)
with self.assertRaises(asyncpg.InFailedSQLTransactionError):
await cur.fetch(1)

self.assertEqual(await self.con.fetch('select 1'), [(1,)])

Expand Down
61 changes: 61 additions & 0 deletions tests/test_transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,67 @@ async def test_transaction_interface_errors(self):
async with tr:
pass

async def test_transaction_commit_when_server_rolls_back(self):
await self.con.execute('''
CREATE TABLE commit_rb (name text);
''')
try:
tr = self.con.transaction()
await tr.start()
await self.con.execute(
"INSERT INTO commit_rb (name) VALUES ('explicit')")
with self.assertRaises(asyncpg.DivisionByZeroError):
await self.con.execute('SELECT 1 / 0')

with self.assertRaisesRegex(
asyncpg.InterfaceError,
'rolled the transaction back'):
await tr.commit()

self.assertTrue(repr(tr).startswith(
'<asyncpg.Transaction state:rolledback'))
self.assertIsNone(self.con._top_xact)
self.assertFalse(self.con.is_in_transaction())
with self.assertRaisesRegex(
asyncpg.InterfaceError,
'already rolled back'):
await tr.rollback()
self.assertEqual(
await self.con.fetchval('SELECT count(*) FROM commit_rb'),
0)

with self.assertRaisesRegex(
asyncpg.InterfaceError,
'rolled the transaction back'):
async with self.con.transaction():
await self.con.execute(
"INSERT INTO commit_rb (name) VALUES ('managed')")
with self.assertRaises(asyncpg.DivisionByZeroError):
await self.con.execute('SELECT 1 / 0')

self.assertIsNone(self.con._top_xact)
self.assertFalse(self.con.is_in_transaction())
self.assertEqual(
await self.con.fetchval(
"SELECT count(*) FROM commit_rb WHERE name = 'managed'"),
0)

async with self.con.transaction():
await self.con.execute(
"INSERT INTO commit_rb (name) VALUES ('control')")
with self.assertRaises(asyncpg.DivisionByZeroError):
async with self.con.transaction():
await self.con.execute('SELECT 1 / 0')

self.assertEqual(
await self.con.fetchval(
"SELECT count(*) FROM commit_rb WHERE name = 'control'"),
1)
finally:
if self.con.is_in_transaction():
await self.con.execute('ROLLBACK')
await self.con.execute('DROP TABLE commit_rb')

async def test_transaction_within_manual_transaction(self):
self.assertIsNone(self.con._top_xact)
self.assertFalse(self.con.is_in_transaction())
Expand Down