Skip to content

Commit

Permalink
Merge pull request #10 from extradosages/multi-transact-context
Browse files Browse the repository at this point in the history
feat: add context-manager dunder methods to `MultiTransact`
  • Loading branch information
zh217 authored Dec 13, 2023
2 parents 5baca1e + 816c9e4 commit 2613272
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,14 @@ assert r['rows'] == [[1], [2], [3]]
You **must** run either `tx.commit()` or `tx.abort()` at the end, otherwise
you will have a resource leak.

To automatically clean up transactions, the return value of `client.multi-transact` can be used as a context-manager which automatically aborts the transaction at the end of the context if it has not already been committed.
```python
with client.multi_transact(True) as tx:
tx.run(':create a {a})
tx.run('?[a] <- [[1]] :put a {a}')
tx.commit()
```

### Mutation callbacks

You can register functions to run whenever mutations are made against stored relations. As an example:
Expand Down
9 changes: 9 additions & 0 deletions pycozo/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,15 @@ class MultiTransact:
def __init__(self, multi_tx):
self.multi_tx = multi_tx

def __enter__(self):
return self

def __exit__(self):
try:
self.abort()
except:
pass

def commit(self):
return self.multi_tx.commit()

Expand Down

0 comments on commit 2613272

Please sign in to comment.