Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/sugar_network/db/metadata.py
blob: 7cba5cea2c6e7619daf216516a6ba05584f77989 (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# Copyright (C) 2011-2013 Aleksey Lim
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import types

from sugar_network import toolkit
from sugar_network.toolkit.router import ACL
from sugar_network.toolkit import http, enforce


#: Xapian term prefix for GUID value
GUID_PREFIX = 'I'

LIST_TYPES = (list, tuple, frozenset, types.GeneratorType)


def indexed_property(property_class=None, *args, **kwargs):

    def getter(func, self):
        value = self[func.__name__]
        return func(self, value)

    def decorate_setter(func, attr):
        attr.prop.setter = lambda self, value: \
                self.set(attr.name, func(self, value))
        attr.prop.on_set = func
        return attr

    def decorate_getter(func):
        enforce(func.__name__ != 'guid',
                "Active property should not have 'guid' name")
        attr = lambda self: getter(func, self)
        attr.setter = lambda func: decorate_setter(func, attr)
        # pylint: disable-msg=W0212
        attr._is_db_property = True
        attr.name = func.__name__
        attr.prop = (property_class or IndexedProperty)(
                attr.name, *args, **kwargs)
        attr.prop.on_get = func
        return attr

    return decorate_getter


stored_property = lambda ** kwargs: indexed_property(StoredProperty, **kwargs)
blob_property = lambda ** kwargs: indexed_property(BlobProperty, **kwargs)


class Metadata(dict):
    """Structure to describe the document.

    Dictionary derived class that contains `Property` objects.

    """

    def __init__(self, cls):
        """
        :param cls:
            class inherited from `db.Resource`

        """
        self._name = cls.__name__.lower()

        slots = {}
        prefixes = {}

        for attr in [getattr(cls, i) for i in dir(cls)]:
            if not hasattr(attr, '_is_db_property'):
                continue

            prop = attr.prop

            if hasattr(prop, 'slot'):
                enforce(prop.slot is None or prop.slot not in slots,
                        'Property %r has a slot already defined for %r in %r',
                        prop.name, slots.get(prop.slot), self.name)
                slots[prop.slot] = prop.name

            if hasattr(prop, 'prefix'):
                enforce(not prop.prefix or prop.prefix not in prefixes,
                        'Property %r has a prefix already defined for %r',
                        prop.name, prefixes.get(prop.prefix))
                prefixes[prop.prefix] = prop.name

            if prop.setter is not None:
                setattr(cls, attr.name, property(attr, prop.setter))
            else:
                setattr(cls, attr.name, property(attr))

            self[prop.name] = prop

    @property
    def name(self):
        """Resource type name."""
        return self._name

    def __getitem__(self, prop_name):
        enforce(prop_name in self, 'There is no %r property in %r',
                prop_name, self.name)
        return dict.__getitem__(self, prop_name)


class Property(object):
    """Basic class to collect information about document property."""

    def __init__(self, name, acl=ACL.PUBLIC, typecast=None,
            parse=None, fmt=None, default=None, sortable_serialise=None):
        """
        :param name:
            property name;
        :param acl:
            access to the property,
            might be an ORed composition of `db.ACCESS_*` constants;
        :param typecast:
            cast property value before storing in the system;
            supported values are `None` (strings), `int` (intergers),
            `float` (floats), `bool` (booleans repesented by symbols
            `0` and `1`),  a sequence of strings (property value should
            confirm one of values from the sequencei);
        :param parse:
            parse property value from a string;
        :param fmt:
            format property value to a string or a list of strings;
        :param default:
            default property value or None;
        :param sortable_serialise:
            cast property value before storing as a srotable value.

        """
        if typecast is bool:
            if fmt is None:
                fmt = lambda x: '1' if x else '0'
            if parse is None:
                parse = lambda x: str(x).lower() in ('true', '1', 'on', 'yes')
        if sortable_serialise is None and typecast in [int, float, bool]:
            sortable_serialise = typecast

        self.setter = None
        self.on_get = lambda self, x: x
        self.on_set = None
        self.name = name
        self.acl = acl
        self.typecast = typecast
        self.parse = parse
        self.fmt = fmt
        self.default = default
        self.sortable_serialise = sortable_serialise

    def assert_access(self, mode):
        """Is access to the property permitted.

        If there are no permissions, function should raise
        `http.Forbidden` exception.

        :param mode:
            one of `db.ACCESS_*` constants
            to specify the access mode

        """
        enforce(mode & self.acl, http.Forbidden,
                '%s access is disabled for %r property',
                ACL.NAMES[mode], self.name)


class StoredProperty(Property):
    """Property to save only in persistent storage, no index."""

    def __init__(self, name, localized=False, typecast=None, fmt=None,
            **kwargs):
        """
        :param: localized:
            property value will be stored per locale;
        :param: **kwargs
            :class:`.Property` arguments

        """
        self.localized = localized

        if localized:
            enforce(typecast is None,
                    'typecast should be None for localized properties')
            enforce(fmt is None,
                    'fmt should be None for localized properties')
            typecast = _localized_typecast
            fmt = _localized_fmt

        Property.__init__(self, name, typecast=typecast, fmt=fmt, **kwargs)


class IndexedProperty(StoredProperty):
    """Property which needs to be indexed."""

    def __init__(self, name, slot=None, prefix=None, full_text=False,
            boolean=False, **kwargs):
        """
        :param slot:
            Xapian document's slot number to add property value to;
        :param prefix:
            Xapian serach term prefix, if `None`, property is not a term;
        :param full_text:
            property takes part in full-text search;
        :param boolean:
            Xapian will use boolean search for this property;
        :param: **kwargs
            :class:`.StoredProperty` arguments

        """
        enforce(name == 'guid' or slot != 0,
                "For %r property, slot '0' is reserved for internal needs",
                name)
        enforce(name == 'guid' or prefix != GUID_PREFIX,
                'For %r property, prefix %r is reserved for internal needs',
                name, GUID_PREFIX)
        enforce(slot is not None or prefix or full_text,
                'For %r property, either slot, prefix or full_text '
                'need to be set',
                name)
        enforce(slot is None or _is_sloted_prop(kwargs.get('typecast')) or
                kwargs.get('sortable_serialise'),
                'Slot can be set only for properties for str, int, float, '
                'bool types, or, for list of these types')

        StoredProperty.__init__(self, name, **kwargs)
        self.slot = slot
        self.prefix = prefix
        self.full_text = full_text
        self.boolean = boolean


class BlobProperty(Property):
    """Binary large objects which needs to be fetched alone, no index."""

    def __init__(self, name, acl=ACL.PUBLIC,
            mime_type='application/octet-stream'):
        """
        :param mime_type:
            MIME type for BLOB content;
            by default, MIME type is application/octet-stream;
        :param: **kwargs
            :class:`.Property` arguments

        """
        Property.__init__(self, name, acl=acl)
        self.mime_type = mime_type


def _is_sloted_prop(typecast):
    if typecast in [None, int, float, bool, str]:
        return True
    if type(typecast) in LIST_TYPES:
        if typecast and [i for i in typecast
                if type(i) in [None, int, float, bool, str]]:
            return True


def _localized_typecast(value):
    if isinstance(value, dict):
        return value
    else:
        return {toolkit.default_lang(): value}


def _localized_fmt(value):
    if isinstance(value, dict):
        return value.values()
    else:
        return [value]