File tree Expand file tree Collapse file tree 1 file changed +10
-0
lines changed
Expand file tree Collapse file tree 1 file changed +10
-0
lines changed Original file line number Diff line number Diff line change 77
88from typing import Any , AsyncContextManager
99from contextlib import asynccontextmanager
10+ from contextvars import ContextVar
1011import asyncio
1112import logging
1213import os
2425POSITIONAL_PARAM_PATTERN = re .compile (r"\$(\d+)" )
2526
2627
28+ in_transaction = ContextVar ("in_transaction" , default = False )
29+
30+
2731class TxnConnection (aiosqlite .Connection ):
2832 def __init__ (self , path : str , ** kwargs ) -> None :
2933 def connector () -> sqlite3 .Connection :
@@ -35,14 +39,20 @@ def connector() -> sqlite3.Connection:
3539
3640 @asynccontextmanager
3741 async def transaction (self ) -> None :
42+ if in_transaction .get ():
43+ yield
44+ return
3845 await self .execute ("BEGIN TRANSACTION" )
46+ token = in_transaction .set (True )
3947 try :
4048 yield
4149 except Exception :
4250 await self .rollback ()
4351 raise
4452 else :
4553 await self .commit ()
54+ finally :
55+ in_transaction .reset (token )
4656
4757 def __execute (self , query : str , * args : Any ):
4858 query = POSITIONAL_PARAM_PATTERN .sub (r"?\1" , query )
You can’t perform that action at this time.
0 commit comments