Skip to content

Commit d675cf3

Browse files
committed
Make nested transactions no-ops on SQLite
1 parent 8adeea8 commit d675cf3

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

mautrix/util/async_db/aiosqlite.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
from typing import Any, AsyncContextManager
99
from contextlib import asynccontextmanager
10+
from contextvars import ContextVar
1011
import asyncio
1112
import logging
1213
import os
@@ -24,6 +25,9 @@
2425
POSITIONAL_PARAM_PATTERN = re.compile(r"\$(\d+)")
2526

2627

28+
in_transaction = ContextVar("in_transaction", default=False)
29+
30+
2731
class 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)

0 commit comments

Comments
 (0)