| 1 |
import importlib |
| 2 |
import inspect |
| 3 |
from importlib.metadata import version |
| 4 |
from types import UnionType |
| 5 |
from typing import ( # noqa: UP035 |
| 6 |
List, |
| 7 |
Sequence, |
| 8 |
Union, |
| 9 |
get_args, |
| 10 |
get_origin, |
| 11 |
) |
| 12 |
|
| 13 |
from pydantic import BaseModel |
| 14 |
from pydantic.fields import FieldInfo |
| 15 |
from pymongo import AsyncMongoClient, IndexModel |
| 16 |
from pymongo.asynchronous.database import AsyncDatabase |
| 17 |
from pymongo.driver_info import DriverInfo |
| 18 |
|
| 19 |
from beanie.exceptions import Deprecation, MongoDBVersionError |
| 20 |
from beanie.odm.actions import ActionRegistry |
| 21 |
from beanie.odm.cache import LRUCache |
| 22 |
from beanie.odm.documents import DocType, Document |
| 23 |
from beanie.odm.fields import ( |
| 24 |
BackLink, |
| 25 |
ExpressionField, |
| 26 |
Link, |
| 27 |
LinkInfo, |
| 28 |
LinkTypes, |
| 29 |
) |
| 30 |
from beanie.odm.interfaces.detector import ModelType |
| 31 |
from beanie.odm.registry import DocsRegistry |
| 32 |
from beanie.odm.settings.document import DocumentSettings, IndexModelField |
| 33 |
from beanie.odm.settings.union_doc import UnionDocSettings |
| 34 |
from beanie.odm.settings.view import ViewSettings |
| 35 |
from beanie.odm.union_doc import UnionDoc, UnionDocType |
| 36 |
from beanie.odm.utils.pydantic import ( |
| 37 |
get_extra_field_info, |
| 38 |
get_model_fields, |
| 39 |
parse_model, |
| 40 |
) |
| 41 |
from beanie.odm.utils.typing import get_index_attributes, is_generic_alias |
| 42 |
from beanie.odm.views import View |
| 43 |
|
| 44 |
_DRIVER_METADATA = DriverInfo(name="beanie", version=version("beanie")) |
| 45 |
|
| 46 |
|
| 47 |
class Output(BaseModel): |
| 48 |
class_name: str |
| 49 |
collection_name: str |
| 50 |
|
| 51 |
|
| 52 |
class Initializer: |
| 53 |
def __init__( |
| 54 |
self, |
| 55 |
database: AsyncDatabase | None = None, |
| 56 |
connection_string: str | None = None, |
| 57 |
document_models: Sequence[ |
| 58 |
type["DocType"] | type["UnionDocType"] | type["View"] | str |
| 59 |
] |
| 60 |
| None = None, |
| 61 |
allow_index_dropping: bool = False, |
| 62 |
recreate_views: bool = False, |
| 63 |
skip_indexes: bool = False, |
| 64 |
): |
| 65 |
""" |
| 66 |
Beanie initializer |
| 67 |
|
| 68 |
:param database: Optional[AsyncDatabase] - pymongo database instance |
| 69 |
Default None. |
| 70 |
:param connection_string: Optional[str] - MongoDB connection string. Default None. |
| 71 |
:param document_models: Optional[Sequence[Union[type[Document], type[UnionDoc], type["View"], str]]] |
| 72 |
- model classes or strings with dot separated paths. Default None |
| 73 |
:param allow_index_dropping: bool - if index dropping is allowed. |
| 74 |
Default False |
| 75 |
:param recreate_views: bool - if views should be recreated. Default False |
| 76 |
:param skip_indexes: bool - if you want to skip working with indexes. Default False |
| 77 |
:return: None |
| 78 |
""" |
| 79 |
|
| 80 |
self.inited_classes: list[type] = [] |
| 81 |
self.allow_index_dropping = allow_index_dropping |
| 82 |
self.skip_indexes = skip_indexes |
| 83 |
self.recreate_views = recreate_views |
| 84 |
|
| 85 |
if (connection_string is None and database is None) or ( |
| 86 |
connection_string is not None and database is not None |
| 87 |
): |
| 88 |
raise ValueError( |
| 89 |
"connection_string parameter or database parameter must be set" |
| 90 |
) |
| 91 |
|
| 92 |
if document_models is None: |
| 93 |
raise ValueError("document_models parameter must be set") |
| 94 |
if connection_string is not None: |
| 95 |
database = AsyncMongoClient( |
| 96 |
connection_string, driver=_DRIVER_METADATA |
| 97 |
).get_default_database() |
| 98 |
|
| 99 |
# append_metadata was added in PyMongo 4.14 and is a valid database name prior to that version |
| 100 |
elif database is not None and callable( |
| 101 |
database.client.append_metadata |
| 102 |
): |
| 103 |
database.client.append_metadata(_DRIVER_METADATA) |
| 104 |
|
| 105 |
self.database: AsyncDatabase = database # type: ignore |
| 106 |
|
| 107 |
sort_order = { |
| 108 |
ModelType.UnionDoc: 0, |
| 109 |
ModelType.Document: 1, |
| 110 |
ModelType.View: 2, |
| 111 |
} |
| 112 |
|
| 113 |
self.document_models: list[ |
| 114 |
type[DocType] | type[UnionDocType] | type[View] |
| 115 |
] = [ |
| 116 |
self.get_model(model) if isinstance(model, str) else model |
| 117 |
for model in document_models |
| 118 |
] |
| 119 |
|
| 120 |
self.fill_docs_registry() |
| 121 |
|
| 122 |
self.document_models.sort( |
| 123 |
key=lambda val: sort_order[val.get_model_type()] |
| 124 |
) |
| 125 |
|
| 126 |
self._database_major_version: int = -1 |
| 127 |
self._existing_collections: list[str] = [] |
| 128 |
|
| 129 |
def __await__(self): |
| 130 |
yield from self._load_cached_info().__await__() |
| 131 |
for model in self.document_models: |
| 132 |
yield from self.init_class(model).__await__() |
| 133 |
|
| 134 |
async def _load_cached_info(self): |
| 135 |
build_info = await self.database.command({"buildInfo": 1}) |
| 136 |
self._database_major_version = int(build_info["version"].split(".")[0]) |
| 137 |
self._existing_collections = await self.database.list_collection_names( |
| 138 |
authorizedCollections=True, nameOnly=True |
| 139 |
) |
| 140 |
|
| 141 |
# General |
| 142 |
def fill_docs_registry(self): |
| 143 |
for model in self.document_models: |
| 144 |
module = inspect.getmodule(model) |
| 145 |
members = inspect.getmembers(module) |
| 146 |
for name, obj in members: |
| 147 |
if not inspect.isclass(obj) or is_generic_alias(obj): |
| 148 |
continue |
| 149 |
|
| 150 |
if issubclass(obj, BaseModel): |
| 151 |
DocsRegistry.register(name, obj) |
| 152 |
|
| 153 |
@staticmethod |
| 154 |
def get_model(dot_path: str) -> type["DocType"]: |
| 155 |
""" |
| 156 |
Get the model by the path in format bar.foo.Model |
| 157 |
|
| 158 |
:param dot_path: str - dot seprated path to the model |
| 159 |
:return: Type[DocType] - class of the model |
| 160 |
""" |
| 161 |
module_name, class_name = None, None |
| 162 |
try: |
| 163 |
module_name, class_name = dot_path.rsplit(".", 1) |
| 164 |
return getattr(importlib.import_module(module_name), class_name) |
| 165 |
|
| 166 |
except ValueError: |
| 167 |
raise ValueError( |
| 168 |
f"'{dot_path}' doesn't have '.' path, eg. path.to.your.model.class" |
| 169 |
) |
| 170 |
|
| 171 |
except AttributeError: |
| 172 |
raise AttributeError( |
| 173 |
f"module '{module_name}' has no class called '{class_name}'" |
| 174 |
) |
| 175 |
|
| 176 |
def init_settings(self, cls: type[Document] | type[View] | type[UnionDoc]): |
| 177 |
""" |
| 178 |
Init Settings |
| 179 |
|
| 180 |
:param cls: Union[Type[Document], Type[View], Type[UnionDoc]] - Class |
| 181 |
to init settings |
| 182 |
:return: None |
| 183 |
""" |
| 184 |
settings_class = getattr(cls, "Settings", None) |
| 185 |
settings_vars = {} |
| 186 |
if settings_class is not None: |
| 187 |
# get all attributes of the Settings subclass (including inherited ones) |
| 188 |
# without magic dunder methods |
| 189 |
settings_vars = { |
| 190 |
attr: getattr(settings_class, attr) |
| 191 |
for attr in dir(settings_class) |
| 192 |
if not attr.startswith("__") |
| 193 |
} |
| 194 |
if issubclass(cls, Document): |
| 195 |
cls._document_settings = parse_model( |
| 196 |
DocumentSettings, settings_vars |
| 197 |
) |
| 198 |
if issubclass(cls, View): |
| 199 |
cls._settings = parse_model(ViewSettings, settings_vars) |
| 200 |
if issubclass(cls, UnionDoc): |
| 201 |
cls._settings = parse_model(UnionDocSettings, settings_vars) |
| 202 |
|
| 203 |
# General. Relations |
| 204 |
|
| 205 |
def detect_link( |
| 206 |
self, field: FieldInfo, field_name: str |
| 207 |
) -> LinkInfo | None: |
| 208 |
""" |
| 209 |
It detects link and returns LinkInfo if any found. |
| 210 |
|
| 211 |
:param field: ModelField |
| 212 |
:return: Optional[LinkInfo] |
| 213 |
""" |
| 214 |
|
| 215 |
origin = get_origin(field.annotation) |
| 216 |
args = get_args(field.annotation) |
| 217 |
classes = [ |
| 218 |
Link, |
| 219 |
BackLink, |
| 220 |
] |
| 221 |
|
| 222 |
for cls in classes: |
| 223 |
# Check if annotation is one of the custom classes |
| 224 |
if get_origin(field.annotation) is cls: |
| 225 |
if cls is Link: |
| 226 |
return LinkInfo( |
| 227 |
field_name=field_name, |
| 228 |
lookup_field_name=field_name, |
| 229 |
document_class=DocsRegistry.evaluate_fr(args[0]), # type: ignore |
| 230 |
link_type=LinkTypes.DIRECT, |
| 231 |
) |
| 232 |
if cls is BackLink: |
| 233 |
return LinkInfo( |
| 234 |
field_name=field_name, |
| 235 |
lookup_field_name=get_extra_field_info( |
| 236 |
field, "original_field" |
| 237 |
), # type: ignore |
| 238 |
document_class=DocsRegistry.evaluate_fr(args[0]), # type: ignore |
| 239 |
link_type=LinkTypes.BACK_DIRECT, |
| 240 |
) |
| 241 |
|
| 242 |
# Check if annotation is List[custom class] or list[custom class] |
| 243 |
elif ( |
| 244 |
origin in (List, list) # noqa: UP006 |
| 245 |
and len(args) == 1 |
| 246 |
and get_origin(args[0]) is cls |
| 247 |
): |
| 248 |
if cls is Link: |
| 249 |
return LinkInfo( |
| 250 |
field_name=field_name, |
| 251 |
lookup_field_name=field_name, |
| 252 |
document_class=DocsRegistry.evaluate_fr( |
| 253 |
get_args(args[0])[0] |
| 254 |
), # type: ignore |
| 255 |
link_type=LinkTypes.LIST, |
| 256 |
) |
| 257 |
if cls is BackLink: |
| 258 |
return LinkInfo( |
| 259 |
field_name=field_name, |
| 260 |
lookup_field_name=get_extra_field_info( # type: ignore |
| 261 |
field, "original_field" |
| 262 |
), |
| 263 |
document_class=DocsRegistry.evaluate_fr( |
| 264 |
get_args(args[0])[0] |
| 265 |
), # type: ignore |
| 266 |
link_type=LinkTypes.BACK_LIST, |
| 267 |
) |
| 268 |
|
| 269 |
# Check if annotation is Optional[custom class] or Optional[List[custom class]] |
| 270 |
elif ( |
| 271 |
(origin is Union or isinstance(field.annotation, UnionType)) |
| 272 |
and len(args) == 2 |
| 273 |
and type(None) in args |
| 274 |
): |
| 275 |
if args[1] is type(None): |
| 276 |
optional = args[0] |
| 277 |
else: |
| 278 |
optional = args[1] |
| 279 |
optional_origin = get_origin(optional) |
| 280 |
optional_args = get_args(optional) |
| 281 |
|
| 282 |
if get_origin(optional) is cls: |
| 283 |
if cls is Link: |
| 284 |
return LinkInfo( |
| 285 |
field_name=field_name, |
| 286 |
lookup_field_name=field_name, |
| 287 |
document_class=DocsRegistry.evaluate_fr( |
| 288 |
optional_args[0] |
| 289 |
), # type: ignore |
| 290 |
link_type=LinkTypes.OPTIONAL_DIRECT, |
| 291 |
) |
| 292 |
if cls is BackLink: |
| 293 |
return LinkInfo( |
| 294 |
field_name=field_name, |
| 295 |
lookup_field_name=get_extra_field_info( |
| 296 |
field, "original_field" |
| 297 |
), |
| 298 |
document_class=DocsRegistry.evaluate_fr( |
| 299 |
optional_args[0] |
| 300 |
), # type: ignore |
| 301 |
link_type=LinkTypes.OPTIONAL_BACK_DIRECT, |
| 302 |
) |
| 303 |
|
| 304 |
elif ( |
| 305 |
optional_origin in (List, list) # noqa: UP006 |
| 306 |
and len(optional_args) == 1 |
| 307 |
and get_origin(optional_args[0]) is cls |
| 308 |
): |
| 309 |
if cls is Link: |
| 310 |
return LinkInfo( |
| 311 |
field_name=field_name, |
| 312 |
lookup_field_name=field_name, |
| 313 |
document_class=DocsRegistry.evaluate_fr( |
| 314 |
get_args(optional_args[0])[0] |
| 315 |
), # type: ignore |
| 316 |
link_type=LinkTypes.OPTIONAL_LIST, |
| 317 |
) |
| 318 |
if cls is BackLink: |
| 319 |
return LinkInfo( |
| 320 |
field_name=field_name, |
| 321 |
lookup_field_name=get_extra_field_info( |
| 322 |
field, "original_field" |
| 323 |
), |
| 324 |
document_class=DocsRegistry.evaluate_fr( |
| 325 |
get_args(optional_args[0])[0] |
| 326 |
), # type: ignore |
| 327 |
link_type=LinkTypes.OPTIONAL_BACK_LIST, |
| 328 |
) |
| 329 |
return None |
| 330 |
|
| 331 |
def check_nested_links(self, link_info: LinkInfo, current_depth: int): |
| 332 |
if current_depth == 1: |
| 333 |
return |
| 334 |
for k, v in get_model_fields(link_info.document_class).items(): |
| 335 |
nested_link_info = self.detect_link(v, k) |
| 336 |
if nested_link_info is None: |
| 337 |
continue |
| 338 |
|
| 339 |
if link_info.nested_links is None: |
| 340 |
link_info.nested_links = {} |
| 341 |
link_info.nested_links[k] = nested_link_info |
| 342 |
new_depth = ( |
| 343 |
current_depth - 1 if current_depth is not None else None |
| 344 |
) |
| 345 |
self.check_nested_links(nested_link_info, current_depth=new_depth) |
| 346 |
|
| 347 |
# Document |
| 348 |
|
| 349 |
@staticmethod |
| 350 |
def set_default_class_vars(cls: type[Document]): |
| 351 |
""" |
| 352 |
Set default class variables. |
| 353 |
|
| 354 |
:param cls: Union[Type[Document], Type[View], Type[UnionDoc]] - Class |
| 355 |
to init settings |
| 356 |
:return: |
| 357 |
""" |
| 358 |
cls._children = dict() |
| 359 |
cls._parent = None |
| 360 |
cls._inheritance_inited = False |
| 361 |
cls._class_id = None |
| 362 |
cls._link_fields = None |
| 363 |
|
| 364 |
@staticmethod |
| 365 |
def init_cache(cls) -> None: |
| 366 |
""" |
| 367 |
Init model's cache |
| 368 |
:return: None |
| 369 |
""" |
| 370 |
if cls.get_settings().use_cache: |
| 371 |
cls._cache = LRUCache( |
| 372 |
capacity=cls.get_settings().cache_capacity, |
| 373 |
expiration_time=cls.get_settings().cache_expiration_time, |
| 374 |
) |
| 375 |
|
| 376 |
def init_document_fields(self, cls) -> None: |
| 377 |
""" |
| 378 |
Init class fields |
| 379 |
:return: None |
| 380 |
""" |
| 381 |
if cls._link_fields is None: |
| 382 |
cls._link_fields = {} |
| 383 |
for k, v in get_model_fields(cls).items(): |
| 384 |
path = v.alias or k |
| 385 |
annotation = getattr(v, "annotation", None) |
| 386 |
resolution = ExpressionField._resolve_field(annotation) |
| 387 |
setattr(cls, k, ExpressionField(path, field_resolution=resolution)) |
| 388 |
|
| 389 |
link_info = self.detect_link(v, k) |
| 390 |
depth_level = cls.get_settings().max_nesting_depths_per_field.get( |
| 391 |
k, None |
| 392 |
) |
| 393 |
if depth_level is None: |
| 394 |
depth_level = cls.get_settings().max_nesting_depth |
| 395 |
if link_info is not None: |
| 396 |
if depth_level > 0 or depth_level is None: |
| 397 |
cls._link_fields[k] = link_info |
| 398 |
self.check_nested_links( |
| 399 |
link_info, current_depth=depth_level |
| 400 |
) |
| 401 |
elif depth_level <= 0: |
| 402 |
link_info.is_fetchable = False |
| 403 |
cls._link_fields[k] = link_info |
| 404 |
|
| 405 |
cls._check_hidden_fields() |
| 406 |
|
| 407 |
@staticmethod |
| 408 |
def init_actions(cls): |
| 409 |
""" |
| 410 |
Init event-based actions |
| 411 |
""" |
| 412 |
ActionRegistry.clean_actions(cls) |
| 413 |
for attr in dir(cls): |
| 414 |
if attr.startswith("_"): # Skip all private/magic attributes |
| 415 |
continue |
| 416 |
|
| 417 |
f = getattr(cls, attr) |
| 418 |
if inspect.isfunction(f) and hasattr(f, "has_action"): |
| 419 |
ActionRegistry.add_action( |
| 420 |
document_class=cls, |
| 421 |
event_types=f.event_types, # type: ignore |
| 422 |
action_direction=f.action_direction, # type: ignore |
| 423 |
funct=f, |
| 424 |
) |
| 425 |
|
| 426 |
async def init_document_collection(self, cls): |
| 427 |
""" |
| 428 |
Init collection for the Document-based class |
| 429 |
:param cls: |
| 430 |
:return: |
| 431 |
""" |
| 432 |
cls.set_database(self.database) |
| 433 |
|
| 434 |
document_settings = cls.get_settings() |
| 435 |
|
| 436 |
# register in the Union Doc |
| 437 |
|
| 438 |
if document_settings.union_doc is not None: |
| 439 |
name = cls.get_settings().name or cls.__name__ |
| 440 |
document_settings.name = document_settings.union_doc.register_doc( |
| 441 |
name, cls |
| 442 |
) |
| 443 |
document_settings.union_doc_alias = name |
| 444 |
|
| 445 |
# set a name |
| 446 |
|
| 447 |
if not document_settings.name: |
| 448 |
document_settings.name = cls.__name__ |
| 449 |
|
| 450 |
# check mongodb version fits |
| 451 |
if ( |
| 452 |
document_settings.timeseries is not None |
| 453 |
and cls._database_major_version < 5 |
| 454 |
): |
| 455 |
raise MongoDBVersionError( |
| 456 |
"Timeseries are supported by MongoDB version 5 and higher" |
| 457 |
) |
| 458 |
|
| 459 |
# create pymongo collection |
| 460 |
if ( |
| 461 |
document_settings.timeseries is not None |
| 462 |
and document_settings.name not in self._existing_collections |
| 463 |
): |
| 464 |
collection = await self.database.create_collection( |
| 465 |
**document_settings.timeseries.build_query( |
| 466 |
document_settings.name |
| 467 |
) |
| 468 |
) |
| 469 |
else: |
| 470 |
collection = self.database[document_settings.name] |
| 471 |
|
| 472 |
cls.set_collection(collection) |
| 473 |
|
| 474 |
async def init_indexes(self, cls, allow_index_dropping: bool = False): |
| 475 |
""" |
| 476 |
Async indexes initializer |
| 477 |
""" |
| 478 |
collection = cls.get_pymongo_collection() |
| 479 |
document_settings = cls.get_settings() |
| 480 |
|
| 481 |
index_information = await collection.index_information() |
| 482 |
|
| 483 |
old_indexes = IndexModelField.from_pymongo_index_information( |
| 484 |
index_information |
| 485 |
) |
| 486 |
new_indexes = [] |
| 487 |
|
| 488 |
# Indexed field wrapped with Indexed() |
| 489 |
indexed_fields = ( |
| 490 |
(k, fvalue, get_index_attributes(fvalue)) |
| 491 |
for k, fvalue in get_model_fields(cls).items() |
| 492 |
) |
| 493 |
found_indexes = [ |
| 494 |
IndexModelField( |
| 495 |
IndexModel( |
| 496 |
[ |
| 497 |
( |
| 498 |
fvalue.alias or k, |
| 499 |
indexed_attrs[0], |
| 500 |
) |
| 501 |
], |
| 502 |
**indexed_attrs[1], |
| 503 |
) |
| 504 |
) |
| 505 |
for k, fvalue, indexed_attrs in indexed_fields |
| 506 |
if indexed_attrs is not None |
| 507 |
] |
| 508 |
|
| 509 |
if document_settings.merge_indexes: |
| 510 |
result: list[IndexModelField] = [] |
| 511 |
for subclass in reversed(cls.mro()): |
| 512 |
if issubclass(subclass, Document) and subclass != Document: |
| 513 |
if subclass not in self.inited_classes and subclass != cls: |
| 514 |
await self.init_class(subclass) |
| 515 |
if subclass.get_settings().indexes: |
| 516 |
result = IndexModelField.merge_indexes( |
| 517 |
result, subclass.get_settings().indexes |
| 518 |
) |
| 519 |
found_indexes = IndexModelField.merge_indexes( |
| 520 |
found_indexes, result |
| 521 |
) |
| 522 |
|
| 523 |
else: |
| 524 |
if document_settings.indexes: |
| 525 |
found_indexes = IndexModelField.merge_indexes( |
| 526 |
found_indexes, document_settings.indexes |
| 527 |
) |
| 528 |
|
| 529 |
new_indexes += found_indexes |
| 530 |
|
| 531 |
# delete indexes |
| 532 |
# Only drop indexes if the user specifically allows for it |
| 533 |
if allow_index_dropping: |
| 534 |
for index in IndexModelField.list_difference( |
| 535 |
old_indexes, new_indexes |
| 536 |
): |
| 537 |
await collection.drop_index(index.name) |
| 538 |
|
| 539 |
# create indices |
| 540 |
if found_indexes: |
| 541 |
new_indexes += await collection.create_indexes( |
| 542 |
IndexModelField.list_to_index_model(new_indexes) |
| 543 |
) |
| 544 |
|
| 545 |
async def init_document(self, cls: type[Document]) -> Output | None: |
| 546 |
""" |
| 547 |
Init Document-based class |
| 548 |
|
| 549 |
:param cls: |
| 550 |
:return: |
| 551 |
""" |
| 552 |
if cls is Document: |
| 553 |
return None |
| 554 |
|
| 555 |
# get db version |
| 556 |
cls._database_major_version = self._database_major_version |
| 557 |
|
| 558 |
own_settings = cls.__dict__.get("Settings") |
| 559 |
class_id_value = getattr(own_settings, "class_id_value", None) |
| 560 |
if cls not in self.inited_classes: |
| 561 |
self.set_default_class_vars(cls) |
| 562 |
self.init_settings(cls) |
| 563 |
|
| 564 |
bases = [b for b in cls.__bases__ if issubclass(b, Document)] |
| 565 |
if len(bases) > 1: |
| 566 |
return None |
| 567 |
parent = bases[0] |
| 568 |
output = await self.init_document(parent) |
| 569 |
if cls.get_settings().is_root and ( |
| 570 |
parent is Document or not parent.get_settings().is_root |
| 571 |
): |
| 572 |
if cls.get_collection_name() is None: |
| 573 |
cls.set_collection_name(cls.__name__) |
| 574 |
output = Output( |
| 575 |
class_name=cls.__name__, |
| 576 |
collection_name=cls.get_collection_name(), |
| 577 |
) |
| 578 |
cls._class_id = ( |
| 579 |
cls.__name__ if class_id_value is None else class_id_value |
| 580 |
) |
| 581 |
cls._inheritance_inited = True |
| 582 |
elif output is not None: |
| 583 |
output.class_name = ( |
| 584 |
f"{output.class_name}.{cls.__name__}" |
| 585 |
if class_id_value is None |
| 586 |
else class_id_value |
| 587 |
) |
| 588 |
cls._class_id = output.class_name |
| 589 |
cls.set_collection_name(output.collection_name) |
| 590 |
parent.add_child(cls._class_id, cls) |
| 591 |
cls._parent = parent # type: ignore |
| 592 |
cls._inheritance_inited = True |
| 593 |
|
| 594 |
await self.init_document_collection(cls) |
| 595 |
if not self.skip_indexes: |
| 596 |
await self.init_indexes(cls, self.allow_index_dropping) |
| 597 |
self.init_document_fields(cls) |
| 598 |
self.init_cache(cls) |
| 599 |
self.init_actions(cls) |
| 600 |
|
| 601 |
self.inited_classes.append(cls) |
| 602 |
|
| 603 |
return output |
| 604 |
|
| 605 |
else: |
| 606 |
if cls._inheritance_inited is True: |
| 607 |
return Output( |
| 608 |
class_name=cls._class_id, |
| 609 |
collection_name=cls.get_collection_name(), |
| 610 |
) |
| 611 |
else: |
| 612 |
return None |
| 613 |
|
| 614 |
# Views |
| 615 |
|
| 616 |
def init_view_fields(self, cls: type[View]) -> None: |
| 617 |
""" |
| 618 |
Init class fields |
| 619 |
:return: None |
| 620 |
""" |
| 621 |
|
| 622 |
if cls._link_fields is None: |
| 623 |
cls._link_fields = {} |
| 624 |
for k, v in get_model_fields(cls).items(): |
| 625 |
path = v.alias or k |
| 626 |
annotation = getattr(v, "annotation", None) |
| 627 |
resolution = ExpressionField._resolve_field(annotation) |
| 628 |
setattr(cls, k, ExpressionField(path, field_resolution=resolution)) |
| 629 |
link_info = self.detect_link(v, k) |
| 630 |
depth_level = cls.get_settings().max_nesting_depths_per_field.get( |
| 631 |
k, None |
| 632 |
) |
| 633 |
if depth_level is None: |
| 634 |
depth_level = cls.get_settings().max_nesting_depth |
| 635 |
if link_info is not None: |
| 636 |
if depth_level > 0: |
| 637 |
cls._link_fields[k] = link_info |
| 638 |
self.check_nested_links( |
| 639 |
link_info, current_depth=depth_level |
| 640 |
) |
| 641 |
elif depth_level <= 0: |
| 642 |
link_info.is_fetchable = False |
| 643 |
cls._link_fields[k] = link_info |
| 644 |
|
| 645 |
def init_view_collection(self, cls: type[View]): |
| 646 |
""" |
| 647 |
Init collection for View |
| 648 |
|
| 649 |
:param cls: |
| 650 |
:return: |
| 651 |
""" |
| 652 |
view_settings = cls.get_settings() |
| 653 |
|
| 654 |
if view_settings.name is None: |
| 655 |
view_settings.name = cls.__name__ |
| 656 |
|
| 657 |
if inspect.isclass(view_settings.source): |
| 658 |
view_settings.source = view_settings.source.get_collection_name() |
| 659 |
|
| 660 |
view_settings.pymongo_db = self.database |
| 661 |
view_settings.pymongo_collection = self.database[view_settings.name] |
| 662 |
|
| 663 |
async def init_view(self, cls: type[View]): |
| 664 |
""" |
| 665 |
Init View-based class |
| 666 |
|
| 667 |
:param cls: |
| 668 |
:return: |
| 669 |
""" |
| 670 |
cls._database_major_version = self._database_major_version |
| 671 |
|
| 672 |
self.init_settings(cls) |
| 673 |
self.init_view_collection(cls) |
| 674 |
self.init_view_fields(cls) |
| 675 |
self.init_cache(cls) |
| 676 |
|
| 677 |
if ( |
| 678 |
self.recreate_views |
| 679 |
or cls._settings.name not in self._existing_collections |
| 680 |
): |
| 681 |
if cls._settings.name in self._existing_collections: |
| 682 |
await cls.get_pymongo_collection().drop() |
| 683 |
|
| 684 |
await self.database.command( |
| 685 |
{ |
| 686 |
"create": cls.get_settings().name, |
| 687 |
"viewOn": cls.get_settings().source, |
| 688 |
"pipeline": cls.get_settings().pipeline, |
| 689 |
} |
| 690 |
) |
| 691 |
|
| 692 |
# Union Doc |
| 693 |
|
| 694 |
async def init_union_doc(self, cls: type[UnionDoc]): |
| 695 |
""" |
| 696 |
Init Union Doc based class |
| 697 |
|
| 698 |
:param cls: |
| 699 |
:return: |
| 700 |
""" |
| 701 |
self.init_settings(cls) |
| 702 |
if cls._settings.name is None: |
| 703 |
cls._settings.name = cls.__name__ |
| 704 |
|
| 705 |
cls._settings.pymongo_db = self.database |
| 706 |
cls._settings.pymongo_collection = self.database[cls._settings.name] |
| 707 |
cls._is_inited = True |
| 708 |
|
| 709 |
# Deprecations |
| 710 |
|
| 711 |
@staticmethod |
| 712 |
def check_deprecations( |
| 713 |
cls: type[Document] | type[View] | type[UnionDoc], |
| 714 |
): |
| 715 |
if hasattr(cls, "Collection"): |
| 716 |
raise Deprecation( |
| 717 |
"Collection inner class is not supported more. " |
| 718 |
"Please use Settings instead. " |
| 719 |
"https://beanie-odm.dev/tutorial/defining-a-document/#settings" |
| 720 |
) |
| 721 |
|
| 722 |
# Final |
| 723 |
|
| 724 |
async def init_class( |
| 725 |
self, cls: type[Document] | type[View] | type[UnionDoc] |
| 726 |
): |
| 727 |
""" |
| 728 |
Init Document, View or UnionDoc based class. |
| 729 |
|
| 730 |
:param cls: |
| 731 |
:return: |
| 732 |
""" |
| 733 |
self.check_deprecations(cls) |
| 734 |
|
| 735 |
if issubclass(cls, Document): |
| 736 |
await self.init_document(cls) |
| 737 |
|
| 738 |
if issubclass(cls, View): |
| 739 |
await self.init_view(cls) |
| 740 |
|
| 741 |
if issubclass(cls, UnionDoc): |
| 742 |
await self.init_union_doc(cls) |
| 743 |
|
| 744 |
if hasattr(cls, "custom_init"): |
| 745 |
await cls.custom_init() # type: ignore |
| 746 |
|
| 747 |
|
| 748 |
async def init_beanie( |
| 749 |
database: AsyncDatabase | None = None, |
| 750 |
connection_string: str | None = None, |
| 751 |
document_models: Sequence[ |
| 752 |
type[Document] | type[UnionDoc] | type["View"] | str |
| 753 |
] |
| 754 |
| None = None, |
| 755 |
allow_index_dropping: bool = False, |
| 756 |
recreate_views: bool = False, |
| 757 |
skip_indexes: bool = False, |
| 758 |
): |
| 759 |
""" |
| 760 |
Beanie initialization |
| 761 |
|
| 762 |
:param database: Optional[AsyncDatabase] - pymongo database instance. Defaults to None. |
| 763 |
:param connection_string: Optional[str] - MongoDB connection string. Defaults to None. |
| 764 |
:param document_models: Optional[Sequence[Union[type[Document], type[UnionDoc], type["View"], str]]] |
| 765 |
- model classes or strings with dot separated paths. Defaults to None. |
| 766 |
:param allow_index_dropping: bool - if index dropping is allowed. |
| 767 |
Defaults to False. |
| 768 |
:param recreate_views: bool - if views should be recreated. Defaults to False. |
| 769 |
:param skip_indexes: bool - if you want to skip working with the indexes. |
| 770 |
Defaults to False. |
| 771 |
:return: None |
| 772 |
""" |
| 773 |
|
| 774 |
await Initializer( |
| 775 |
database=database, |
| 776 |
connection_string=connection_string, |
| 777 |
document_models=document_models, |
| 778 |
allow_index_dropping=allow_index_dropping, |
| 779 |
recreate_views=recreate_views, |
| 780 |
skip_indexes=skip_indexes, |
| 781 |
) |