Skip to content

Commit

Permalink
Support nested ReadTransaction (#59)
Browse files Browse the repository at this point in the history
* Support nested ReadTransaction

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
davidbrochart and pre-commit-ci[bot] authored Jan 4, 2024
1 parent 2fe8a4b commit 985be7d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 20 deletions.
21 changes: 3 additions & 18 deletions python/pycrdt/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ class Transaction:
_txn: _Transaction | None
_nb: int

def __init__(self, doc: Doc) -> None:
def __init__(self, doc: Doc, _txn: _Transaction | None = None) -> None:
self._doc = doc
self._txn = None
self._txn = _txn
self._nb = 0

def __enter__(self) -> Transaction:
Expand Down Expand Up @@ -45,19 +45,4 @@ def __exit__(


class ReadTransaction(Transaction):
def __init__(self, doc: Doc, _txn: _Transaction) -> None:
self._doc = doc
self._txn = _txn

def __enter__(self) -> Transaction:
self._doc._txn = self
return self

def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
self._txn = None
self._doc._txn = None
pass
16 changes: 14 additions & 2 deletions tests/test_transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@ def test_callback_transaction():
events = []

def callback(event):
events.append(str(event.target))
target = event.target
doc = target.doc
with doc.transaction():
events.append(target.to_py())
with doc.transaction():
events.append(str(target))

text.observe(callback)
array.observe(callback)
Expand All @@ -25,4 +30,11 @@ def callback(event):
text += " world"
array.append(1)
map_["foo"] = "bar"
assert events == ["hello world", "[1.0]", '{"foo":"bar"}']
assert events == [
"hello world",
"hello world",
[1.0],
"[1.0]",
{"foo": "bar"},
'{"foo":"bar"}',
]

0 comments on commit 985be7d

Please sign in to comment.