-
Notifications
You must be signed in to change notification settings - Fork 186
/
transaction.py
63 lines (47 loc) · 1.58 KB
/
transaction.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import asyncio
from enum import Enum
import aiormq
class TransactionStates(Enum):
created = 'created'
commited = 'commited'
rolled_back = 'rolled back'
started = 'started'
class Transaction:
def __str__(self):
return self.state.value
def __init__(self, channel):
self.loop = channel.loop
self._channel = channel
self.state = TransactionStates.created # type: TransactionStates
@property
def channel(self) -> aiormq.Channel:
if self._channel is None:
raise RuntimeError("Channel not opened")
if self._channel.is_closed:
raise RuntimeError('Closed channel')
return self._channel
async def select(self, timeout=None) -> aiormq.spec.Tx.SelectOk:
result = await asyncio.wait_for(
self.channel.tx_select(), timeout=timeout
)
self.state = TransactionStates.started
return result
async def rollback(self, timeout=None):
result = await asyncio.wait_for(
self.channel.tx_rollback(), timeout=timeout
)
self.state = TransactionStates.rolled_back
return result
async def commit(self, timeout=None):
result = await asyncio.wait_for(
self.channel.tx_commit(), timeout=timeout
)
self.state = TransactionStates.commited
return result
async def __aenter__(self):
return await self.select()
async def __aexit__(self, exc_type, exc_val, exc_tb):
if exc_type:
await self.rollback()
else:
await self.commit()