diff options
Diffstat (limited to 'ick2/trans.py')
-rw-r--r-- | ick2/trans.py | 76 |
1 files changed, 76 insertions, 0 deletions
diff --git a/ick2/trans.py b/ick2/trans.py new file mode 100644 index 0000000..a66dd41 --- /dev/null +++ b/ick2/trans.py @@ -0,0 +1,76 @@ +# Copyright (C) 2018 Lars Wirzenius +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + + +import ick2 + + +class TransactionalResource: + + def __init__(self, state, kind, rid): + self.state = state + self.kind = kind + self.rid = rid + if state.has_resource(kind, rid): + self.resource = state.get_resource(kind, rid) + else: + self.resource = ick2.resource_from_dict({}) + + methods = [ + 'as_dict', + '__getitem__', + '__setitem__', + '__contains__', + '__len__', + ] + for method in methods: + setattr(self, method, getattr(self.resource, method)) + + def __enter__(self): + return self.resource + + def __exit__(self, exc_type, value, traceback): + if exc_type is None: + self.state.write_resource(self.kind, self.rid, self.resource) + + +class TransactionalState: + + def __init__(self, state): + self.state = state + + def new(self, kind, rid): + return TransactionalResource(self.state, kind, rid) + + def modify(self, kind, rid): + return TransactionalResource(self.state, kind, rid) + + def get_resource_kinds(self): + return self.state.get_resource_kinds() + + def get_resource_ids(self, kind): + return self.state.get_resource_ids(kind) + + def has_resource(self, kind, rid): + return self.state.has_resource(kind, rid) + + def get_resource(self, kind, rid): + return self.state.get_resource(kind, rid) + + def get_resources(self, kind): + return self.state.get_resources(kind) + + def remove_resource(self, kind, rid): + self.state.remove_resource(kind, rid) |