summaryrefslogtreecommitdiff
path: root/ick2/trans.py
blob: c5dc22f84ca11db38a0b38386367abaaba8986fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# Copyright (C) 2018-2019  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):
        if not self.state.has_resource(kind, rid):
            raise ick2.NotFound(kind=kind, rid=rid)
        return TransactionalResource(self.state, kind, rid)

    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)