autonomous-app 0.3.0__py3-none-any.whl → 0.3.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- autonomous/__init__.py +1 -1
- autonomous/ai/audioagent.py +1 -1
- autonomous/ai/imageagent.py +1 -1
- autonomous/ai/jsonagent.py +1 -1
- autonomous/ai/models/openai.py +81 -53
- autonomous/ai/oaiagent.py +1 -14
- autonomous/ai/textagent.py +1 -1
- autonomous/auth/autoauth.py +10 -10
- autonomous/auth/user.py +17 -2
- autonomous/db/__init__.py +42 -0
- autonomous/db/base/__init__.py +33 -0
- autonomous/db/base/common.py +62 -0
- autonomous/db/base/datastructures.py +476 -0
- autonomous/db/base/document.py +1230 -0
- autonomous/db/base/fields.py +767 -0
- autonomous/db/base/metaclasses.py +468 -0
- autonomous/db/base/utils.py +22 -0
- autonomous/db/common.py +79 -0
- autonomous/db/connection.py +472 -0
- autonomous/db/context_managers.py +313 -0
- autonomous/db/dereference.py +291 -0
- autonomous/db/document.py +1141 -0
- autonomous/db/errors.py +165 -0
- autonomous/db/fields.py +2732 -0
- autonomous/db/mongodb_support.py +24 -0
- autonomous/db/pymongo_support.py +80 -0
- autonomous/db/queryset/__init__.py +28 -0
- autonomous/db/queryset/base.py +2033 -0
- autonomous/db/queryset/field_list.py +88 -0
- autonomous/db/queryset/manager.py +58 -0
- autonomous/db/queryset/queryset.py +189 -0
- autonomous/db/queryset/transform.py +527 -0
- autonomous/db/queryset/visitor.py +189 -0
- autonomous/db/signals.py +59 -0
- autonomous/logger.py +3 -0
- autonomous/model/autoattr.py +56 -41
- autonomous/model/automodel.py +88 -34
- {autonomous_app-0.3.0.dist-info → autonomous_app-0.3.1.dist-info}/METADATA +2 -2
- autonomous_app-0.3.1.dist-info/RECORD +60 -0
- {autonomous_app-0.3.0.dist-info → autonomous_app-0.3.1.dist-info}/WHEEL +1 -1
- autonomous_app-0.3.0.dist-info/RECORD +0 -35
- {autonomous_app-0.3.0.dist-info → autonomous_app-0.3.1.dist-info}/LICENSE +0 -0
- {autonomous_app-0.3.0.dist-info → autonomous_app-0.3.1.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
import itertools
|
|
2
|
+
import warnings
|
|
3
|
+
|
|
4
|
+
from autonomous.db.base.common import _document_registry
|
|
5
|
+
from autonomous.db.base.fields import (
|
|
6
|
+
BaseField,
|
|
7
|
+
ComplexBaseField,
|
|
8
|
+
ObjectIdField,
|
|
9
|
+
)
|
|
10
|
+
from autonomous.db.common import _import_class
|
|
11
|
+
from autonomous.db.errors import InvalidDocumentError
|
|
12
|
+
from autonomous.db.queryset import (
|
|
13
|
+
DO_NOTHING,
|
|
14
|
+
DoesNotExist,
|
|
15
|
+
MultipleObjectsReturned,
|
|
16
|
+
QuerySetManager,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__all__ = ("DocumentMetaclass", "TopLevelDocumentMetaclass")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DocumentMetaclass(type):
|
|
23
|
+
"""Metaclass for all documents."""
|
|
24
|
+
|
|
25
|
+
# TODO lower complexity of this method
|
|
26
|
+
def __new__(mcs, name, bases, attrs):
|
|
27
|
+
flattened_bases = mcs._get_bases(bases)
|
|
28
|
+
super_new = super().__new__
|
|
29
|
+
|
|
30
|
+
# If a base class just call super
|
|
31
|
+
metaclass = attrs.get("my_metaclass")
|
|
32
|
+
if metaclass and issubclass(metaclass, DocumentMetaclass):
|
|
33
|
+
return super_new(mcs, name, bases, attrs)
|
|
34
|
+
|
|
35
|
+
attrs["_is_document"] = attrs.get("_is_document", False)
|
|
36
|
+
attrs["_cached_reference_fields"] = []
|
|
37
|
+
|
|
38
|
+
# EmbeddedDocuments could have meta data for inheritance
|
|
39
|
+
if "meta" in attrs:
|
|
40
|
+
attrs["_meta"] = attrs.pop("meta")
|
|
41
|
+
|
|
42
|
+
# EmbeddedDocuments should inherit meta data
|
|
43
|
+
if "_meta" not in attrs:
|
|
44
|
+
meta = MetaDict()
|
|
45
|
+
for base in flattened_bases[::-1]:
|
|
46
|
+
# Add any mixin metadata from plain objects
|
|
47
|
+
if hasattr(base, "meta"):
|
|
48
|
+
meta.merge(base.meta)
|
|
49
|
+
elif hasattr(base, "_meta"):
|
|
50
|
+
meta.merge(base._meta)
|
|
51
|
+
attrs["_meta"] = meta
|
|
52
|
+
attrs["_meta"]["abstract"] = (
|
|
53
|
+
False # 789: EmbeddedDocument shouldn't inherit abstract
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
# If allow_inheritance is True, add a "_cls" string field to the attrs
|
|
57
|
+
if attrs["_meta"].get("allow_inheritance"):
|
|
58
|
+
StringField = _import_class("StringField")
|
|
59
|
+
attrs["_cls"] = StringField()
|
|
60
|
+
|
|
61
|
+
# Handle document Fields
|
|
62
|
+
|
|
63
|
+
# Merge all fields from subclasses
|
|
64
|
+
doc_fields = {}
|
|
65
|
+
for base in flattened_bases[::-1]:
|
|
66
|
+
if hasattr(base, "_fields"):
|
|
67
|
+
doc_fields.update(base._fields)
|
|
68
|
+
|
|
69
|
+
# Standard object mixin - merge in any Fields
|
|
70
|
+
if not hasattr(base, "_meta"):
|
|
71
|
+
base_fields = {}
|
|
72
|
+
for attr_name, attr_value in base.__dict__.items():
|
|
73
|
+
if not isinstance(attr_value, BaseField):
|
|
74
|
+
continue
|
|
75
|
+
attr_value.name = attr_name
|
|
76
|
+
if not attr_value.db_field:
|
|
77
|
+
attr_value.db_field = attr_name
|
|
78
|
+
base_fields[attr_name] = attr_value
|
|
79
|
+
|
|
80
|
+
doc_fields.update(base_fields)
|
|
81
|
+
|
|
82
|
+
# Discover any document fields
|
|
83
|
+
field_names = {}
|
|
84
|
+
for attr_name, attr_value in attrs.items():
|
|
85
|
+
if not isinstance(attr_value, BaseField):
|
|
86
|
+
continue
|
|
87
|
+
attr_value.name = attr_name
|
|
88
|
+
if not attr_value.db_field:
|
|
89
|
+
attr_value.db_field = attr_name
|
|
90
|
+
doc_fields[attr_name] = attr_value
|
|
91
|
+
|
|
92
|
+
# Count names to ensure no db_field redefinitions
|
|
93
|
+
field_names[attr_value.db_field] = (
|
|
94
|
+
field_names.get(attr_value.db_field, 0) + 1
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
# Ensure no duplicate db_fields
|
|
98
|
+
duplicate_db_fields = [k for k, v in field_names.items() if v > 1]
|
|
99
|
+
if duplicate_db_fields:
|
|
100
|
+
msg = "Multiple db_fields defined for: %s " % ", ".join(duplicate_db_fields)
|
|
101
|
+
raise InvalidDocumentError(msg)
|
|
102
|
+
|
|
103
|
+
# Set _fields and db_field maps
|
|
104
|
+
attrs["_fields"] = doc_fields
|
|
105
|
+
attrs["_db_field_map"] = {
|
|
106
|
+
k: getattr(v, "db_field", k) for k, v in doc_fields.items()
|
|
107
|
+
}
|
|
108
|
+
attrs["_reverse_db_field_map"] = {
|
|
109
|
+
v: k for k, v in attrs["_db_field_map"].items()
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
attrs["_fields_ordered"] = tuple(
|
|
113
|
+
i[1]
|
|
114
|
+
for i in sorted((v.creation_counter, v.name) for v in doc_fields.values())
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
#
|
|
118
|
+
# Set document hierarchy
|
|
119
|
+
#
|
|
120
|
+
superclasses = ()
|
|
121
|
+
class_name = [name]
|
|
122
|
+
for base in flattened_bases:
|
|
123
|
+
if not getattr(base, "_is_base_cls", True) and not getattr(
|
|
124
|
+
base, "_meta", {}
|
|
125
|
+
).get("abstract", True):
|
|
126
|
+
# Collate hierarchy for _cls and _subclasses
|
|
127
|
+
class_name.append(base.__name__)
|
|
128
|
+
|
|
129
|
+
if hasattr(base, "_meta"):
|
|
130
|
+
# Warn if allow_inheritance isn't set and prevent
|
|
131
|
+
# inheritance of classes where inheritance is set to False
|
|
132
|
+
allow_inheritance = base._meta.get("allow_inheritance")
|
|
133
|
+
if not allow_inheritance and not base._meta.get("abstract"):
|
|
134
|
+
raise ValueError(
|
|
135
|
+
"Document %s may not be subclassed. "
|
|
136
|
+
'To enable inheritance, use the "allow_inheritance" meta attribute.'
|
|
137
|
+
% base.__name__
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
# Get superclasses from last base superclass
|
|
141
|
+
document_bases = [b for b in flattened_bases if hasattr(b, "_class_name")]
|
|
142
|
+
if document_bases:
|
|
143
|
+
superclasses = document_bases[0]._superclasses
|
|
144
|
+
superclasses += (document_bases[0]._class_name,)
|
|
145
|
+
|
|
146
|
+
_cls = ".".join(reversed(class_name))
|
|
147
|
+
attrs["_class_name"] = _cls
|
|
148
|
+
attrs["_superclasses"] = superclasses
|
|
149
|
+
attrs["_subclasses"] = (_cls,)
|
|
150
|
+
attrs["_types"] = attrs["_subclasses"] # TODO depreciate _types
|
|
151
|
+
|
|
152
|
+
# Create the new_class
|
|
153
|
+
new_class = super_new(mcs, name, bases, attrs)
|
|
154
|
+
|
|
155
|
+
# Set _subclasses
|
|
156
|
+
for base in document_bases:
|
|
157
|
+
if _cls not in base._subclasses:
|
|
158
|
+
base._subclasses += (_cls,)
|
|
159
|
+
base._types = base._subclasses # TODO depreciate _types
|
|
160
|
+
|
|
161
|
+
(
|
|
162
|
+
Document,
|
|
163
|
+
EmbeddedDocument,
|
|
164
|
+
DictField,
|
|
165
|
+
CachedReferenceField,
|
|
166
|
+
) = mcs._import_classes()
|
|
167
|
+
|
|
168
|
+
if issubclass(new_class, Document):
|
|
169
|
+
new_class._collection = None
|
|
170
|
+
|
|
171
|
+
# Add class to the _document_registry
|
|
172
|
+
_document_registry[new_class._class_name] = new_class
|
|
173
|
+
|
|
174
|
+
# Handle delete rules
|
|
175
|
+
for field in new_class._fields.values():
|
|
176
|
+
f = field
|
|
177
|
+
if f.owner_document is None:
|
|
178
|
+
f.owner_document = new_class
|
|
179
|
+
delete_rule = getattr(f, "reverse_delete_rule", DO_NOTHING)
|
|
180
|
+
if isinstance(f, CachedReferenceField):
|
|
181
|
+
if issubclass(new_class, EmbeddedDocument):
|
|
182
|
+
raise InvalidDocumentError(
|
|
183
|
+
"CachedReferenceFields is not allowed in EmbeddedDocuments"
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
if f.auto_sync:
|
|
187
|
+
f.start_listener()
|
|
188
|
+
|
|
189
|
+
f.document_type._cached_reference_fields.append(f)
|
|
190
|
+
|
|
191
|
+
if isinstance(f, ComplexBaseField) and hasattr(f, "field"):
|
|
192
|
+
delete_rule = getattr(f.field, "reverse_delete_rule", DO_NOTHING)
|
|
193
|
+
if isinstance(f, DictField) and delete_rule != DO_NOTHING:
|
|
194
|
+
msg = (
|
|
195
|
+
"Reverse delete rules are not supported "
|
|
196
|
+
"for %s (field: %s)" % (field.__class__.__name__, field.name)
|
|
197
|
+
)
|
|
198
|
+
raise InvalidDocumentError(msg)
|
|
199
|
+
|
|
200
|
+
f = field.field
|
|
201
|
+
|
|
202
|
+
if delete_rule != DO_NOTHING:
|
|
203
|
+
if issubclass(new_class, EmbeddedDocument):
|
|
204
|
+
msg = (
|
|
205
|
+
"Reverse delete rules are not supported for "
|
|
206
|
+
"EmbeddedDocuments (field: %s)" % field.name
|
|
207
|
+
)
|
|
208
|
+
raise InvalidDocumentError(msg)
|
|
209
|
+
f.document_type.register_delete_rule(new_class, field.name, delete_rule)
|
|
210
|
+
|
|
211
|
+
if (
|
|
212
|
+
field.name
|
|
213
|
+
and hasattr(Document, field.name)
|
|
214
|
+
and EmbeddedDocument not in new_class.mro()
|
|
215
|
+
):
|
|
216
|
+
msg = "%s is a document method and not a valid field name" % field.name
|
|
217
|
+
raise InvalidDocumentError(msg)
|
|
218
|
+
|
|
219
|
+
return new_class
|
|
220
|
+
|
|
221
|
+
@classmethod
|
|
222
|
+
def _get_bases(mcs, bases):
|
|
223
|
+
if isinstance(bases, BasesTuple):
|
|
224
|
+
return bases
|
|
225
|
+
seen = []
|
|
226
|
+
bases = mcs.__get_bases(bases)
|
|
227
|
+
unique_bases = (b for b in bases if not (b in seen or seen.append(b)))
|
|
228
|
+
return BasesTuple(unique_bases)
|
|
229
|
+
|
|
230
|
+
@classmethod
|
|
231
|
+
def __get_bases(mcs, bases):
|
|
232
|
+
for base in bases:
|
|
233
|
+
if base is object:
|
|
234
|
+
continue
|
|
235
|
+
yield base
|
|
236
|
+
yield from mcs.__get_bases(base.__bases__)
|
|
237
|
+
|
|
238
|
+
@classmethod
|
|
239
|
+
def _import_classes(mcs):
|
|
240
|
+
Document = _import_class("Document")
|
|
241
|
+
EmbeddedDocument = _import_class("EmbeddedDocument")
|
|
242
|
+
DictField = _import_class("DictField")
|
|
243
|
+
CachedReferenceField = _import_class("CachedReferenceField")
|
|
244
|
+
return Document, EmbeddedDocument, DictField, CachedReferenceField
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
class TopLevelDocumentMetaclass(DocumentMetaclass):
|
|
248
|
+
"""Metaclass for top-level documents (i.e. documents that have their own
|
|
249
|
+
collection in the database.
|
|
250
|
+
"""
|
|
251
|
+
|
|
252
|
+
def __new__(mcs, name, bases, attrs):
|
|
253
|
+
flattened_bases = mcs._get_bases(bases)
|
|
254
|
+
super_new = super().__new__
|
|
255
|
+
|
|
256
|
+
# Set default _meta data if base class, otherwise get user defined meta
|
|
257
|
+
if attrs.get("my_metaclass") == TopLevelDocumentMetaclass:
|
|
258
|
+
# defaults
|
|
259
|
+
attrs["_meta"] = {
|
|
260
|
+
"abstract": True,
|
|
261
|
+
"max_documents": None,
|
|
262
|
+
"max_size": None,
|
|
263
|
+
"ordering": [], # default ordering applied at runtime
|
|
264
|
+
"indexes": [], # indexes to be ensured at runtime
|
|
265
|
+
"id_field": None,
|
|
266
|
+
"index_background": False,
|
|
267
|
+
"index_opts": None,
|
|
268
|
+
"delete_rules": None,
|
|
269
|
+
# allow_inheritance can be True, False, and None. True means
|
|
270
|
+
# "allow inheritance", False means "don't allow inheritance",
|
|
271
|
+
# None means "do whatever your parent does, or don't allow
|
|
272
|
+
# inheritance if you're a top-level class".
|
|
273
|
+
"allow_inheritance": None,
|
|
274
|
+
}
|
|
275
|
+
attrs["_is_base_cls"] = True
|
|
276
|
+
attrs["_meta"].update(attrs.get("meta", {}))
|
|
277
|
+
else:
|
|
278
|
+
attrs["_meta"] = attrs.get("meta", {})
|
|
279
|
+
# Explicitly set abstract to false unless set
|
|
280
|
+
attrs["_meta"]["abstract"] = attrs["_meta"].get("abstract", False)
|
|
281
|
+
attrs["_is_base_cls"] = False
|
|
282
|
+
|
|
283
|
+
# Set flag marking as document class - as opposed to an object mixin
|
|
284
|
+
attrs["_is_document"] = True
|
|
285
|
+
|
|
286
|
+
# Ensure queryset_class is inherited
|
|
287
|
+
if "objects" in attrs:
|
|
288
|
+
manager = attrs["objects"]
|
|
289
|
+
if hasattr(manager, "queryset_class"):
|
|
290
|
+
attrs["_meta"]["queryset_class"] = manager.queryset_class
|
|
291
|
+
|
|
292
|
+
# Clean up top level meta
|
|
293
|
+
if "meta" in attrs:
|
|
294
|
+
del attrs["meta"]
|
|
295
|
+
|
|
296
|
+
# Find the parent document class
|
|
297
|
+
parent_doc_cls = [
|
|
298
|
+
b for b in flattened_bases if b.__class__ == TopLevelDocumentMetaclass
|
|
299
|
+
]
|
|
300
|
+
parent_doc_cls = None if not parent_doc_cls else parent_doc_cls[0]
|
|
301
|
+
|
|
302
|
+
# Prevent classes setting collection different to their parents
|
|
303
|
+
# If parent wasn't an abstract class
|
|
304
|
+
if (
|
|
305
|
+
parent_doc_cls
|
|
306
|
+
and "collection" in attrs.get("_meta", {})
|
|
307
|
+
and not parent_doc_cls._meta.get("abstract", True)
|
|
308
|
+
):
|
|
309
|
+
msg = "Trying to set a collection on a subclass (%s)" % name
|
|
310
|
+
warnings.warn(msg, SyntaxWarning)
|
|
311
|
+
del attrs["_meta"]["collection"]
|
|
312
|
+
|
|
313
|
+
# Ensure abstract documents have abstract bases
|
|
314
|
+
if attrs.get("_is_base_cls") or attrs["_meta"].get("abstract"):
|
|
315
|
+
if parent_doc_cls and not parent_doc_cls._meta.get("abstract", False):
|
|
316
|
+
msg = "Abstract document cannot have non-abstract base"
|
|
317
|
+
raise ValueError(msg)
|
|
318
|
+
return super_new(mcs, name, bases, attrs)
|
|
319
|
+
|
|
320
|
+
# Merge base class metas.
|
|
321
|
+
# Uses a special MetaDict that handles various merging rules
|
|
322
|
+
meta = MetaDict()
|
|
323
|
+
for base in flattened_bases[::-1]:
|
|
324
|
+
# Add any mixin metadata from plain objects
|
|
325
|
+
if hasattr(base, "meta"):
|
|
326
|
+
meta.merge(base.meta)
|
|
327
|
+
elif hasattr(base, "_meta"):
|
|
328
|
+
meta.merge(base._meta)
|
|
329
|
+
|
|
330
|
+
# Set collection in the meta if its callable
|
|
331
|
+
if getattr(base, "_is_document", False) and not base._meta.get("abstract"):
|
|
332
|
+
collection = meta.get("collection", None)
|
|
333
|
+
if callable(collection):
|
|
334
|
+
meta["collection"] = collection(base)
|
|
335
|
+
|
|
336
|
+
meta.merge(attrs.get("_meta", {})) # Top level meta
|
|
337
|
+
|
|
338
|
+
# Only simple classes (i.e. direct subclasses of Document) may set
|
|
339
|
+
# allow_inheritance to False. If the base Document allows inheritance,
|
|
340
|
+
# none of its subclasses can override allow_inheritance to False.
|
|
341
|
+
simple_class = all(
|
|
342
|
+
b._meta.get("abstract") for b in flattened_bases if hasattr(b, "_meta")
|
|
343
|
+
)
|
|
344
|
+
if (
|
|
345
|
+
not simple_class
|
|
346
|
+
and meta["allow_inheritance"] is False
|
|
347
|
+
and not meta["abstract"]
|
|
348
|
+
):
|
|
349
|
+
raise ValueError(
|
|
350
|
+
"Only direct subclasses of Document may set "
|
|
351
|
+
'"allow_inheritance" to False'
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
# Set default collection name
|
|
355
|
+
if "collection" not in meta:
|
|
356
|
+
meta["collection"] = (
|
|
357
|
+
"".join("_%s" % c if c.isupper() else c for c in name)
|
|
358
|
+
.strip("_")
|
|
359
|
+
.lower()
|
|
360
|
+
)
|
|
361
|
+
attrs["_meta"] = meta
|
|
362
|
+
|
|
363
|
+
# Call super and get the new class
|
|
364
|
+
new_class = super_new(mcs, name, bases, attrs)
|
|
365
|
+
|
|
366
|
+
meta = new_class._meta
|
|
367
|
+
|
|
368
|
+
# Set index specifications
|
|
369
|
+
meta["index_specs"] = new_class._build_index_specs(meta["indexes"])
|
|
370
|
+
|
|
371
|
+
# If collection is a callable - call it and set the value
|
|
372
|
+
collection = meta.get("collection")
|
|
373
|
+
if callable(collection):
|
|
374
|
+
new_class._meta["collection"] = collection(new_class)
|
|
375
|
+
|
|
376
|
+
# Provide a default queryset unless exists or one has been set
|
|
377
|
+
if "objects" not in dir(new_class):
|
|
378
|
+
new_class.objects = QuerySetManager()
|
|
379
|
+
|
|
380
|
+
# Validate the fields and set primary key if needed
|
|
381
|
+
for field_name, field in new_class._fields.items():
|
|
382
|
+
if field.primary_key:
|
|
383
|
+
# Ensure only one primary key is set
|
|
384
|
+
current_pk = new_class._meta.get("id_field")
|
|
385
|
+
if current_pk and current_pk != field_name:
|
|
386
|
+
raise ValueError("Cannot override primary key field")
|
|
387
|
+
|
|
388
|
+
# Set primary key
|
|
389
|
+
if not current_pk:
|
|
390
|
+
new_class._meta["id_field"] = field_name
|
|
391
|
+
new_class.id = field
|
|
392
|
+
|
|
393
|
+
# If the document doesn't explicitly define a primary key field, create
|
|
394
|
+
# one. Make it an ObjectIdField and give it a non-clashing name ("id"
|
|
395
|
+
# by default, but can be different if that one's taken).
|
|
396
|
+
if not new_class._meta.get("id_field"):
|
|
397
|
+
id_name, id_db_name = mcs.get_auto_id_names(new_class)
|
|
398
|
+
new_class._meta["id_field"] = id_name
|
|
399
|
+
new_class._fields[id_name] = ObjectIdField(db_field=id_db_name)
|
|
400
|
+
new_class._fields[id_name].name = id_name
|
|
401
|
+
new_class.id = new_class._fields[id_name]
|
|
402
|
+
new_class._db_field_map[id_name] = id_db_name
|
|
403
|
+
new_class._reverse_db_field_map[id_db_name] = id_name
|
|
404
|
+
|
|
405
|
+
# Prepend the ID field to _fields_ordered (so that it's *always*
|
|
406
|
+
# the first field).
|
|
407
|
+
new_class._fields_ordered = (id_name,) + new_class._fields_ordered
|
|
408
|
+
|
|
409
|
+
# Merge in exceptions with parent hierarchy.
|
|
410
|
+
exceptions_to_merge = (DoesNotExist, MultipleObjectsReturned)
|
|
411
|
+
module = attrs.get("__module__")
|
|
412
|
+
for exc in exceptions_to_merge:
|
|
413
|
+
name = exc.__name__
|
|
414
|
+
parents = tuple(
|
|
415
|
+
getattr(base, name) for base in flattened_bases if hasattr(base, name)
|
|
416
|
+
) or (exc,)
|
|
417
|
+
|
|
418
|
+
# Create a new exception and set it as an attribute on the new
|
|
419
|
+
# class.
|
|
420
|
+
exception = type(name, parents, {"__module__": module})
|
|
421
|
+
setattr(new_class, name, exception)
|
|
422
|
+
|
|
423
|
+
return new_class
|
|
424
|
+
|
|
425
|
+
@classmethod
|
|
426
|
+
def get_auto_id_names(mcs, new_class):
|
|
427
|
+
"""Find a name for the automatic ID field for the given new class.
|
|
428
|
+
|
|
429
|
+
Return a two-element tuple where the first item is the field name (i.e.
|
|
430
|
+
the attribute name on the object) and the second element is the DB
|
|
431
|
+
field name (i.e. the name of the key stored in MongoDB).
|
|
432
|
+
|
|
433
|
+
Defaults to ('id', '_id'), or generates a non-clashing name in the form
|
|
434
|
+
of ('auto_id_X', '_auto_id_X') if the default name is already taken.
|
|
435
|
+
"""
|
|
436
|
+
id_name, id_db_name = ("id", "_id")
|
|
437
|
+
existing_fields = {field_name for field_name in new_class._fields}
|
|
438
|
+
existing_db_fields = {v.db_field for v in new_class._fields.values()}
|
|
439
|
+
if id_name not in existing_fields and id_db_name not in existing_db_fields:
|
|
440
|
+
return id_name, id_db_name
|
|
441
|
+
|
|
442
|
+
id_basename, id_db_basename, i = ("auto_id", "_auto_id", 0)
|
|
443
|
+
for i in itertools.count():
|
|
444
|
+
id_name = f"{id_basename}_{i}"
|
|
445
|
+
id_db_name = f"{id_db_basename}_{i}"
|
|
446
|
+
if id_name not in existing_fields and id_db_name not in existing_db_fields:
|
|
447
|
+
return id_name, id_db_name
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
class MetaDict(dict):
|
|
451
|
+
"""Custom dictionary for meta classes.
|
|
452
|
+
Handles the merging of set indexes
|
|
453
|
+
"""
|
|
454
|
+
|
|
455
|
+
_merge_options = ("indexes",)
|
|
456
|
+
|
|
457
|
+
def merge(self, new_options):
|
|
458
|
+
for k, v in new_options.items():
|
|
459
|
+
if k in self._merge_options:
|
|
460
|
+
self[k] = self.get(k, []) + v
|
|
461
|
+
else:
|
|
462
|
+
self[k] = v
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
class BasesTuple(tuple):
|
|
466
|
+
"""Special class to handle introspection of bases tuple in __new__"""
|
|
467
|
+
|
|
468
|
+
pass
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class LazyRegexCompiler:
|
|
5
|
+
"""Descriptor to allow lazy compilation of regex"""
|
|
6
|
+
|
|
7
|
+
def __init__(self, pattern, flags=0):
|
|
8
|
+
self._pattern = pattern
|
|
9
|
+
self._flags = flags
|
|
10
|
+
self._compiled_regex = None
|
|
11
|
+
|
|
12
|
+
@property
|
|
13
|
+
def compiled_regex(self):
|
|
14
|
+
if self._compiled_regex is None:
|
|
15
|
+
self._compiled_regex = re.compile(self._pattern, self._flags)
|
|
16
|
+
return self._compiled_regex
|
|
17
|
+
|
|
18
|
+
def __get__(self, instance, owner):
|
|
19
|
+
return self.compiled_regex
|
|
20
|
+
|
|
21
|
+
def __set__(self, instance, value):
|
|
22
|
+
raise AttributeError("Can not set attribute LazyRegexCompiler")
|
autonomous/db/common.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import importlib
|
|
2
|
+
|
|
3
|
+
_class_registry_cache = {}
|
|
4
|
+
_field_list_cache = []
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _import_class(cls_name):
|
|
8
|
+
"""Cache mechanism for imports.
|
|
9
|
+
|
|
10
|
+
Due to complications of circular imports autonomous.db needs to do lots of
|
|
11
|
+
inline imports in functions. This is inefficient as classes are
|
|
12
|
+
imported repeated throughout the autonomous.db code. This is
|
|
13
|
+
compounded by some recursive functions requiring inline imports.
|
|
14
|
+
|
|
15
|
+
:mod:`autonomous.db.common` provides a single point to import all these
|
|
16
|
+
classes. Circular imports aren't an issue as it dynamically imports the
|
|
17
|
+
class when first needed. Subsequent calls to the
|
|
18
|
+
:func:`~autonomous.db.common._import_class` can then directly retrieve the
|
|
19
|
+
class from the :data:`autonomous.db.common._class_registry_cache`.
|
|
20
|
+
"""
|
|
21
|
+
if cls_name in _class_registry_cache:
|
|
22
|
+
return _class_registry_cache.get(cls_name)
|
|
23
|
+
|
|
24
|
+
doc_classes = (
|
|
25
|
+
"Document",
|
|
26
|
+
"DynamicEmbeddedDocument",
|
|
27
|
+
"EmbeddedDocument",
|
|
28
|
+
"MapReduceDocument",
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
# Field Classes
|
|
32
|
+
if not _field_list_cache:
|
|
33
|
+
from autonomous.db.fields import __all__ as fields
|
|
34
|
+
|
|
35
|
+
_field_list_cache.extend(fields)
|
|
36
|
+
from autonomous.db.base.fields import __all__ as fields
|
|
37
|
+
|
|
38
|
+
_field_list_cache.extend(fields)
|
|
39
|
+
|
|
40
|
+
field_classes = _field_list_cache
|
|
41
|
+
|
|
42
|
+
deref_classes = ("DeReference",)
|
|
43
|
+
|
|
44
|
+
if cls_name == "BaseDocument":
|
|
45
|
+
from autonomous.db.base import document as module
|
|
46
|
+
|
|
47
|
+
import_classes = ["BaseDocument"]
|
|
48
|
+
elif cls_name in doc_classes:
|
|
49
|
+
from autonomous.db import document as module
|
|
50
|
+
|
|
51
|
+
import_classes = doc_classes
|
|
52
|
+
elif cls_name in field_classes:
|
|
53
|
+
from autonomous.db import fields as module
|
|
54
|
+
|
|
55
|
+
import_classes = field_classes
|
|
56
|
+
elif cls_name in deref_classes:
|
|
57
|
+
from autonomous.db import dereference as module
|
|
58
|
+
|
|
59
|
+
import_classes = deref_classes
|
|
60
|
+
elif cls_name == "AutoModel":
|
|
61
|
+
from autonomous.model import automodel as module
|
|
62
|
+
|
|
63
|
+
import_classes = [cls_name]
|
|
64
|
+
else:
|
|
65
|
+
try:
|
|
66
|
+
module_name, model_name = (
|
|
67
|
+
cls_name.rsplit(".", 1)
|
|
68
|
+
if "." in cls_name
|
|
69
|
+
else (f"models.{cls_name.lower()}", cls_name)
|
|
70
|
+
)
|
|
71
|
+
module = importlib.import_module(module_name)
|
|
72
|
+
import_classes = [cls_name]
|
|
73
|
+
except Exception as e:
|
|
74
|
+
raise Exception(f"{e} \n No import set for: {cls_name}")
|
|
75
|
+
|
|
76
|
+
for cls in import_classes:
|
|
77
|
+
_class_registry_cache[cls] = getattr(module, cls)
|
|
78
|
+
|
|
79
|
+
return _class_registry_cache.get(cls_name)
|