Skip to content

Commit

Permalink
Make tables context managers
Browse files Browse the repository at this point in the history
  • Loading branch information
gvx committed May 26, 2021
1 parent c62ccec commit c6702ae
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
31 changes: 31 additions & 0 deletions tests/test_wurm.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,3 +460,34 @@ class Test:
from wurm import typemaps
assert (list(typemaps.columns_for('field', Test)) ==
['field_0', 'field_1'])


def test_contextmanager(connection):
p = Point(1, 1)
p.insert()
with p:
p.x = 100
Point.del_object(p)
p, = Point
assert p == Point(100, 1)


def test_no_contextmanager(connection):
p = Point(1, 1)
p.insert()
p.x = 100
Point.del_object(p)
p, = Point
assert p == Point(1, 1)


def test_contextmanager_2(connection):
p = Point(1, 1)
p.insert()
with pytest.raises(KeyboardInterrupt):
with p:
p.x = 100
raise KeyboardInterrupt
Point.del_object(p)
p, = Point
assert p == Point(1, 1)
16 changes: 16 additions & 0 deletions wurm/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,15 @@ def display_owner(self):
The above will not create a new table, but subclasses of
``HasOwner`` will have a field called ``owner`` and a method
called ``display_owner``.
Models are context managers, so one could write::
with MyTable.query(field=value) as obj:
obj.field = other_value
This automatically calls :meth:`commit` on ``obj`` as long as
no exception is raised inside the ``with``-block, in which case
``obj`` is left in a dirty state.
"""
__id_map__: ClassVar[dict]
__fields_info__: ClassVar[Dict[str, type]]
Expand Down Expand Up @@ -305,6 +314,13 @@ def _encode_row(self):
for column, cooked
in to_stored(key, ty, getattr(self, key)).items()}

def __enter__(self):
return self

def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
self.commit() # FIXME: insert if new?


@dataclass
class WithoutRowid(BaseTable, abstract=True):
Expand Down

0 comments on commit c6702ae

Please sign in to comment.