-
Notifications
You must be signed in to change notification settings - Fork 62
/
builder.py
353 lines (299 loc) · 13.8 KB
/
builder.py
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
"""Builder module
A builder connect a :class:`umongo.document.Template` with a
:class:`umongo.instance.BaseInstance` by generating an
:class:`umongo.document.Implementation`.
"""
import re
import inspect
from copy import copy
import marshmallow as ma
from .template import Template, Implementation
from .data_proxy import data_proxy_factory
from .document import DocumentTemplate, DocumentOpts, DocumentImplementation
from .embedded_document import (
EmbeddedDocumentTemplate, EmbeddedDocumentOpts, EmbeddedDocumentImplementation)
from .exceptions import DocumentDefinitionError, NotRegisteredDocumentError
from .schema import Schema
from .indexes import parse_index
from . import fields
def camel_to_snake(name):
tmp_str = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', tmp_str).lower()
def _is_child(bases):
"""Find if the given inheritance leeds to a child document (i.e.
a document that shares the same collection with a parent)
"""
return any(b for b in bases if issubclass(b, DocumentImplementation) and not b.opts.abstract)
def _is_child_embedded_document(bases):
"""Same thing than _is_child, but for EmbeddedDocument...
"""
return any(b for b in bases if issubclass(b, EmbeddedDocumentImplementation) and
not b.opts.abstract)
def _on_need_add_id_field(bases, fields_dict):
"""
If the given fields make no reference to `_id`, add an `id` field
(type ObjectId, dump_only=True, attribute=`_id`) to handle it
"""
def find_id_field(fields_dict):
for name, field in fields_dict.items():
# Skip fake fields present in schema (e.g. `post_load` decorated function)
if not isinstance(field, ma.fields.Field):
continue
if (name == '_id' and not field.attribute) or field.attribute == '_id':
return name
return None
# Search among parents for the id field
for base in bases:
schema = base()
name = find_id_field(schema.fields)
if name is not None:
return name
# Search among our own fields
name = find_id_field(fields_dict)
if name is not None:
return name
# No id field found, add a default one
fields_dict['id'] = fields.ObjectIdField(attribute='_id', dump_only=True)
return 'id'
def _add_child_field(name, fields_dict):
fields_dict['cls'] = fields.StringField(attribute='_cls', default=name, dump_only=True)
def _collect_schema_attrs(template):
"""
Split dict between schema fields and non-fields elements and retrieve
marshmallow tags if any.
"""
schema_fields = {}
schema_non_fields = {}
nmspc = {}
# Collect schema attributes up the MRO to get attributes from Mixins
for tmpl in inspect.getmro(template):
# Stop when reaching Doc or EmbeddedDoc template as this is already
# covered by document inheritance
if tmpl != template and issubclass(tmpl, Template):
break
for key, item in tmpl.__dict__.items():
if hasattr(item, '__marshmallow_hook__'):
# Decorated special functions (e.g. `post_load`)
schema_non_fields.setdefault(key, item)
elif isinstance(item, ma.fields.Field):
# Given the fields provided by the template are going to be
# customized in the implementation, we copy them to avoid
# overwriting if two implementations are created
schema_fields.setdefault(key, copy(item))
else:
nmspc.setdefault(key, item)
return nmspc, schema_fields, schema_non_fields
def _collect_indexes(meta, schema_nmspc, bases):
"""
Retrieve all indexes (custom defined in meta class, by inheritances
and unique attribut in fields)
"""
indexes = []
is_child = _is_child(bases)
# First collect parent indexes (including inherited field's unique indexes)
for base in bases:
if issubclass(base, DocumentImplementation):
indexes += base.opts.indexes
# Then get our own custom indexes
if is_child:
custom_indexes = [
parse_index(x, base_compound_field='_cls')
for x in getattr(meta, 'indexes', ())
]
else:
custom_indexes = [parse_index(x) for x in getattr(meta, 'indexes', ())]
indexes += custom_indexes
if is_child:
indexes.append(parse_index('_cls'))
# Finally parse our own fields (i.e. not inherited) for unique indexes
def parse_field(mongo_path, path, field):
if field.unique:
index = {'unique': True, 'key': [mongo_path]}
if not field.required or field.allow_none:
index['sparse'] = True
if is_child:
index['key'].append('_cls')
indexes.append(parse_index(index))
for name, field in schema_nmspc.items():
parse_field(name or field.attribute, name, field)
if hasattr(field, 'map_to_field'):
field.map_to_field(name or field.attribute, name, parse_field)
return indexes
def _build_document_opts(instance, template, name, nmspc, bases):
kwargs = {}
meta = nmspc.get('Meta')
collection_name = getattr(meta, 'collection_name', None)
kwargs['instance'] = instance
kwargs['template'] = template
kwargs['abstract'] = getattr(meta, 'abstract', False)
kwargs['allow_inheritance'] = getattr(meta, 'allow_inheritance', None)
kwargs['is_child'] = _is_child(bases)
kwargs['strict'] = getattr(meta, 'strict', True)
# Handle option inheritance and integrity checks
for base in bases:
if not issubclass(base, DocumentImplementation):
continue
popts = base.opts
if not popts.allow_inheritance:
raise DocumentDefinitionError("Document %r doesn't allow inheritance" % base)
if kwargs['abstract'] and not popts.abstract:
raise DocumentDefinitionError(
"Abstract document should have all it parents abstract")
if popts.collection_name:
if collection_name:
raise DocumentDefinitionError(
"Cannot redefine collection_name in a child, use abstract instead")
collection_name = popts.collection_name
if collection_name:
if kwargs['abstract']:
raise DocumentDefinitionError(
'Abstract document cannot define collection_name')
elif not kwargs['abstract']:
# Determine the collection name from the class name
collection_name = camel_to_snake(name)
return DocumentOpts(collection_name=collection_name, **kwargs)
def _build_embedded_document_opts(instance, template, name, nmspc, bases):
kwargs = {}
meta = nmspc.get('Meta')
kwargs['instance'] = instance
kwargs['template'] = template
kwargs['abstract'] = getattr(meta, 'abstract', False)
kwargs['allow_inheritance'] = getattr(meta, 'allow_inheritance', True)
kwargs['is_child'] = _is_child_embedded_document(bases)
kwargs['strict'] = getattr(meta, 'strict', True)
# Handle option inheritance and integrity checks
for base in bases:
if not issubclass(base, EmbeddedDocumentImplementation):
continue
popts = base.opts
if not popts.allow_inheritance:
raise DocumentDefinitionError("EmbeddedDocument %r doesn't allow inheritance" % base)
if kwargs['abstract'] and not popts.abstract:
raise DocumentDefinitionError(
"Abstract embedded document should have all it parents abstract")
return EmbeddedDocumentOpts(**kwargs)
class BaseBuilder:
"""
A builder connect a :class:`umongo.document.Template` with a
:class:`umongo.instance.BaseInstance` by generating an
:class:`umongo.document.Implementation`.
.. note:: This class should not be used directly, it should be inherited by
concrete implementations such as :class:`umongo.frameworks.pymongo.PyMongoBuilder`
"""
BASE_DOCUMENT_CLS = None
def __init__(self, instance):
assert self.BASE_DOCUMENT_CLS
self.instance = instance
self._templates_lookup = {
DocumentTemplate: self.BASE_DOCUMENT_CLS,
EmbeddedDocumentTemplate: EmbeddedDocumentImplementation
}
def _convert_bases(self, bases):
"Replace template parents by their implementation inside this instance"
converted_bases = []
for base in bases:
assert not issubclass(base, Implementation), \
'Document cannot inherit of implementations'
if issubclass(base, Template):
if base not in self._templates_lookup:
raise NotRegisteredDocumentError('Unknown document `%r`' % base)
converted_bases.append(self._templates_lookup[base])
else:
converted_bases.append(base)
return tuple(converted_bases)
def _patch_field(self, field):
# Recursively set the `instance` attribute to all fields
field.instance = self.instance
if isinstance(field, fields.ListField):
self._patch_field(field.inner)
elif isinstance(field, fields.DictField):
if field.key_field:
self._patch_field(field.key_field)
if field.value_field:
self._patch_field(field.value_field)
elif isinstance(field, fields.EmbeddedField):
for embedded_field in field.schema.fields.values():
self._patch_field(embedded_field)
def _build_schema(self, template, schema_bases, schema_fields, schema_non_fields):
# Recursively set the `instance` attribute to all fields
for field in schema_fields.values():
self._patch_field(field)
# Finally build the schema class
schema_nmspc = {}
schema_nmspc.update(schema_fields)
schema_nmspc.update(schema_non_fields)
schema_nmspc['MA_BASE_SCHEMA_CLS'] = template.MA_BASE_SCHEMA_CLS
return type('%sSchema' % template.__name__, schema_bases, schema_nmspc)
def build_document_from_template(self, template):
"""
Generate a :class:`umongo.document.DocumentImplementation` for this
instance from the given :class:`umongo.document.DocumentTemplate`.
"""
assert issubclass(template, DocumentTemplate)
name = template.__name__
bases = self._convert_bases(template.__bases__)
opts = _build_document_opts(self.instance, template, name, template.__dict__, bases)
nmspc, schema_fields, schema_non_fields = _collect_schema_attrs(template)
nmspc['opts'] = opts
# Create schema by retrieving inherited schema classes
schema_bases = tuple([base.Schema for base in bases
if hasattr(base, 'Schema')])
if not schema_bases:
schema_bases = (Schema, )
nmspc['pk_field'] = _on_need_add_id_field(schema_bases, schema_fields)
# If Document is a child, _cls field must be added to the schema
if opts.is_child:
_add_child_field(name, schema_fields)
schema_cls = self._build_schema(template, schema_bases, schema_fields, schema_non_fields)
nmspc['Schema'] = schema_cls
schema = schema_cls()
nmspc['schema'] = schema
nmspc['DataProxy'] = data_proxy_factory(name, schema, strict=opts.strict)
# _build_document_opts cannot determine the indexes given we need to
# visit the document's fields which weren't defined at this time
opts.indexes = _collect_indexes(nmspc.get('Meta'), schema.fields, bases)
implementation = type(name, bases, nmspc)
self._templates_lookup[template] = implementation
# Notify the parent & grand parents of the newborn !
for base in bases:
for parent in inspect.getmro(base):
if (not issubclass(parent, DocumentImplementation) or
parent is DocumentImplementation):
continue
parent.opts.offspring.add(implementation)
return implementation
def build_embedded_document_from_template(self, template):
"""
Generate a :class:`umongo.document.EmbeddedDocumentImplementation` for this
instance from the given :class:`umongo.document.EmbeddedDocumentTemplate`.
"""
assert issubclass(template, EmbeddedDocumentTemplate)
name = template.__name__
bases = self._convert_bases(template.__bases__)
opts = _build_embedded_document_opts(
self.instance, template, name, template.__dict__, bases)
nmspc, schema_fields, schema_non_fields = _collect_schema_attrs(template)
nmspc['opts'] = opts
# If EmbeddedDocument is a child, _cls field must be added to the schema
if opts.is_child:
_add_child_field(name, schema_fields)
# Create schema by retrieving inherited schema classes
schema_bases = tuple([base.Schema for base in bases
if hasattr(base, 'Schema')])
if not schema_bases:
schema_bases = (Schema, )
schema_cls = self._build_schema(template, schema_bases, schema_fields, schema_non_fields)
nmspc['Schema'] = schema_cls
schema = schema_cls()
nmspc['schema'] = schema
nmspc['DataProxy'] = data_proxy_factory(name, schema, strict=opts.strict)
implementation = type(name, bases, nmspc)
self._templates_lookup[template] = implementation
# Notify the parent & grand parents of the newborn !
for base in bases:
for parent in inspect.getmro(base):
if (not issubclass(parent, EmbeddedDocumentImplementation) or
parent is EmbeddedDocumentImplementation):
continue
parent.opts.offspring.add(implementation)
return implementation