| 1 |
import asyncio |
| 2 |
from collections import OrderedDict |
| 3 |
from dataclasses import dataclass |
| 4 |
from enum import Enum |
| 5 |
from typing import ( |
| 6 |
TYPE_CHECKING, |
| 7 |
Any, |
| 8 |
Generic, |
| 9 |
TypeVar, |
| 10 |
get_args, |
| 11 |
) |
| 12 |
|
| 13 |
from bson import DBRef, ObjectId |
| 14 |
from bson.errors import InvalidId |
| 15 |
from pydantic import ( |
| 16 |
BaseModel, |
| 17 |
GetCoreSchemaHandler, |
| 18 |
GetJsonSchemaHandler, |
| 19 |
TypeAdapter, |
| 20 |
) |
| 21 |
from pydantic.json_schema import JsonSchemaValue |
| 22 |
from pydantic_core import core_schema |
| 23 |
from pydantic_core.core_schema import CoreSchema, ValidationInfo |
| 24 |
from pymongo import ASCENDING, IndexModel |
| 25 |
|
| 26 |
from beanie.odm.enums import SortDirection |
| 27 |
from beanie.odm.operators.find.comparison import ( |
| 28 |
GT, |
| 29 |
GTE, |
| 30 |
LT, |
| 31 |
LTE, |
| 32 |
NE, |
| 33 |
Eq, |
| 34 |
In, |
| 35 |
) |
| 36 |
from beanie.odm.registry import DocsRegistry |
| 37 |
from beanie.odm.utils.parsing import parse_obj |
| 38 |
from beanie.odm.utils.pydantic import get_model_fields |
| 39 |
|
| 40 |
if TYPE_CHECKING: |
| 41 |
from beanie.odm.documents import DocType |
| 42 |
|
| 43 |
|
| 44 |
@dataclass(frozen=True) |
| 45 |
class IndexedAnnotation: |
| 46 |
_indexed: tuple[int, dict[str, Any]] |
| 47 |
|
| 48 |
|
| 49 |
def Indexed(typ=None, index_type=ASCENDING, **kwargs: Any): |
| 50 |
""" |
| 51 |
If `typ` is defined, returns a subclass of `typ` with an extra attribute |
| 52 |
`_indexed` as a tuple: |
| 53 |
- Index 0: `index_type` such as `pymongo.ASCENDING` |
| 54 |
- Index 1: `kwargs` passed to `IndexModel` |
| 55 |
When instantiated the type of the result will actually be `typ`. |
| 56 |
|
| 57 |
When `typ` is not defined, returns an `IndexedAnnotation` instance, to be |
| 58 |
used as metadata in `Annotated` fields. |
| 59 |
|
| 60 |
Example: |
| 61 |
```py |
| 62 |
# Both fields would have the same behavior |
| 63 |
class MyModel(BaseModel): |
| 64 |
field1: Indexed(str, unique=True) |
| 65 |
field2: Annotated[str, Indexed(unique=True)] |
| 66 |
``` |
| 67 |
""" |
| 68 |
if typ is None: |
| 69 |
return IndexedAnnotation(_indexed=(index_type, kwargs)) |
| 70 |
|
| 71 |
class NewType(typ): |
| 72 |
_indexed = (index_type, kwargs) |
| 73 |
|
| 74 |
def __new__(cls, *args: Any, **kwargs: Any): |
| 75 |
return typ.__new__(typ, *args, **kwargs) |
| 76 |
|
| 77 |
@classmethod |
| 78 |
def __get_pydantic_core_schema__( |
| 79 |
cls, _source_type: type[Any], _handler: GetCoreSchemaHandler |
| 80 |
) -> CoreSchema: |
| 81 |
custom_type = getattr(typ, "__get_pydantic_core_schema__", None) |
| 82 |
if custom_type is not None: |
| 83 |
return custom_type(_source_type, _handler) |
| 84 |
|
| 85 |
return core_schema.no_info_after_validator_function( |
| 86 |
lambda v: v, core_schema.simple_ser_schema(typ.__name__) |
| 87 |
) |
| 88 |
|
| 89 |
NewType.__name__ = f"Indexed {typ.__name__}" |
| 90 |
return NewType |
| 91 |
|
| 92 |
|
| 93 |
class PydanticObjectId(ObjectId): |
| 94 |
""" |
| 95 |
Object Id field. Compatible with Pydantic. |
| 96 |
""" |
| 97 |
|
| 98 |
@classmethod |
| 99 |
def _validate(cls, v): |
| 100 |
if isinstance(v, bytes): |
| 101 |
v = v.decode("utf-8") |
| 102 |
try: |
| 103 |
return PydanticObjectId(v) |
| 104 |
except (InvalidId, TypeError): |
| 105 |
raise ValueError("Id must be of type PydanticObjectId") |
| 106 |
|
| 107 |
@classmethod |
| 108 |
def __get_pydantic_core_schema__( |
| 109 |
cls, source_type: type[Any], handler: GetCoreSchemaHandler |
| 110 |
) -> CoreSchema: |
| 111 |
definition = core_schema.definition_reference_schema( |
| 112 |
"PydanticObjectId" |
| 113 |
) # used for deduplication |
| 114 |
|
| 115 |
return core_schema.definitions_schema( |
| 116 |
definition, |
| 117 |
[ |
| 118 |
core_schema.json_or_python_schema( |
| 119 |
python_schema=core_schema.no_info_plain_validator_function( |
| 120 |
cls._validate |
| 121 |
), |
| 122 |
json_schema=core_schema.no_info_after_validator_function( |
| 123 |
cls._validate, |
| 124 |
core_schema.str_schema( |
| 125 |
pattern="^[0-9a-f]{24}$", |
| 126 |
min_length=24, |
| 127 |
max_length=24, |
| 128 |
), |
| 129 |
), |
| 130 |
serialization=core_schema.plain_serializer_function_ser_schema( |
| 131 |
lambda instance: str(instance), when_used="json" |
| 132 |
), |
| 133 |
ref=definition["schema_ref"], |
| 134 |
) |
| 135 |
], |
| 136 |
) |
| 137 |
|
| 138 |
@classmethod |
| 139 |
def __get_pydantic_json_schema__( |
| 140 |
cls, |
| 141 |
schema: core_schema.CoreSchema, |
| 142 |
handler: GetJsonSchemaHandler, # type: ignore |
| 143 |
) -> JsonSchemaValue: |
| 144 |
""" |
| 145 |
Results such schema: |
| 146 |
```json |
| 147 |
{ |
| 148 |
"components": { |
| 149 |
"schemas": { |
| 150 |
"Item": { |
| 151 |
"properties": { |
| 152 |
"id": { |
| 153 |
"$ref": "#/components/schemas/PydanticObjectId" |
| 154 |
} |
| 155 |
}, |
| 156 |
"type": "object", |
| 157 |
"title": "Item" |
| 158 |
}, |
| 159 |
"PydanticObjectId": { |
| 160 |
"type": "string", |
| 161 |
"maxLength": 24, |
| 162 |
"minLength": 24, |
| 163 |
"pattern": "^[0-9a-f]{24}$", |
| 164 |
"example": "5eb7cf5a86d9755df3a6c593" |
| 165 |
} |
| 166 |
} |
| 167 |
} |
| 168 |
} |
| 169 |
``` |
| 170 |
""" |
| 171 |
|
| 172 |
json_schema = handler(schema) |
| 173 |
schema_to_update = handler.resolve_ref_schema(json_schema) |
| 174 |
schema_to_update.update(example="5eb7cf5a86d9755df3a6c593") |
| 175 |
return json_schema |
| 176 |
|
| 177 |
|
| 178 |
BeanieObjectId = PydanticObjectId |
| 179 |
|
| 180 |
|
| 181 |
@dataclass(frozen=True) |
| 182 |
class FieldResolution: |
| 183 |
"""Immutable metadata attached to ExpressionField for query-time |
| 184 |
path resolution. |
| 185 |
|
| 186 |
Tracks the nested model class (for alias resolution during field |
| 187 |
access) and whether the path crosses a Link/BackLink boundary |
| 188 |
(for DBRef translation at query time). |
| 189 |
""" |
| 190 |
|
| 191 |
model_class: type | None = None |
| 192 |
is_link: bool = False |
| 193 |
|
| 194 |
|
| 195 |
class ExpressionField(str): |
| 196 |
def __new__(cls, path, field_resolution=None): |
| 197 |
instance = super().__new__(cls, path) |
| 198 |
instance._field_resolution = ( |
| 199 |
field_resolution |
| 200 |
if field_resolution is not None |
| 201 |
else FieldResolution() |
| 202 |
) |
| 203 |
return instance |
| 204 |
|
| 205 |
@staticmethod |
| 206 |
def _resolve_field(annotation) -> FieldResolution: |
| 207 |
"""Resolve a field annotation to a :class:`FieldResolution`. |
| 208 |
|
| 209 |
Unwraps ``Optional[X]``, ``Union[X, ...]``, ``List[X]`` and |
| 210 |
similar generic wrappers to find the nested ``BaseModel`` |
| 211 |
subclass. ``Link[X]`` and ``BackLink[X]`` are resolved to |
| 212 |
the linked model **and** flagged with ``is_link=True`` so that |
| 213 |
the query layer can perform DBRef path translation at runtime. |
| 214 |
""" |
| 215 |
if annotation is None: |
| 216 |
return FieldResolution() |
| 217 |
|
| 218 |
# Direct BaseModel subclass (embedded document) |
| 219 |
if isinstance(annotation, type) and issubclass(annotation, BaseModel): |
| 220 |
return FieldResolution(model_class=annotation) |
| 221 |
|
| 222 |
origin = getattr(annotation, "__origin__", None) |
| 223 |
args = getattr(annotation, "__args__", None) |
| 224 |
|
| 225 |
# Link[X] / BackLink[X] — resolve to X but mark as link |
| 226 |
if origin is not None and ( |
| 227 |
origin is Link |
| 228 |
or origin is BackLink |
| 229 |
or ( |
| 230 |
isinstance(origin, type) |
| 231 |
and issubclass(origin, (Link, BackLink)) |
| 232 |
) |
| 233 |
): |
| 234 |
if args: |
| 235 |
for arg in args: |
| 236 |
if arg is type(None): |
| 237 |
continue |
| 238 |
if isinstance(arg, type) and issubclass(arg, BaseModel): |
| 239 |
return FieldResolution(model_class=arg, is_link=True) |
| 240 |
nested = ExpressionField._resolve_field(arg) |
| 241 |
if nested.model_class is not None: |
| 242 |
return FieldResolution( |
| 243 |
model_class=nested.model_class, is_link=True |
| 244 |
) |
| 245 |
return FieldResolution(is_link=True) |
| 246 |
|
| 247 |
# Other generics: Optional, Union, List, etc. |
| 248 |
if args: |
| 249 |
for arg in args: |
| 250 |
if arg is type(None): |
| 251 |
continue |
| 252 |
if isinstance(arg, type) and issubclass(arg, BaseModel): |
| 253 |
return FieldResolution(model_class=arg) |
| 254 |
nested = ExpressionField._resolve_field(arg) |
| 255 |
if nested.model_class is not None: |
| 256 |
return nested |
| 257 |
|
| 258 |
return FieldResolution() |
| 259 |
|
| 260 |
def __getitem__(self, item): |
| 261 |
""" |
| 262 |
Get sub field |
| 263 |
|
| 264 |
:param item: name of the subfield |
| 265 |
:return: ExpressionField |
| 266 |
""" |
| 267 |
return ExpressionField( |
| 268 |
f"{self}.{item}", |
| 269 |
field_resolution=FieldResolution( |
| 270 |
is_link=self._field_resolution.is_link |
| 271 |
), |
| 272 |
) |
| 273 |
|
| 274 |
def __getattr__(self, item): |
| 275 |
"""Get sub field, resolving aliases from nested Pydantic models. |
| 276 |
|
| 277 |
Alias resolution is performed through the model class carried |
| 278 |
in ``_field_resolution``. The ``is_link`` flag is propagated |
| 279 |
from parent to child so that downstream query code can |
| 280 |
translate DBRef paths at runtime. |
| 281 |
""" |
| 282 |
if item.startswith("_"): |
| 283 |
raise AttributeError(item) |
| 284 |
|
| 285 |
resolution = self._field_resolution |
| 286 |
if resolution.model_class is not None: |
| 287 |
fields = get_model_fields(resolution.model_class) |
| 288 |
if item in fields: |
| 289 |
field_info = fields[item] |
| 290 |
alias = field_info.alias if field_info.alias else item |
| 291 |
annotation = getattr(field_info, "annotation", None) |
| 292 |
child = ExpressionField._resolve_field(annotation) |
| 293 |
# Propagate is_link from parent when child is not |
| 294 |
# itself a new link boundary. |
| 295 |
if resolution.is_link and not child.is_link: |
| 296 |
child = FieldResolution( |
| 297 |
model_class=child.model_class, is_link=True |
| 298 |
) |
| 299 |
return ExpressionField( |
| 300 |
f"{self}.{alias}", field_resolution=child |
| 301 |
) |
| 302 |
|
| 303 |
return ExpressionField( |
| 304 |
f"{self}.{item}", |
| 305 |
field_resolution=FieldResolution(is_link=resolution.is_link), |
| 306 |
) |
| 307 |
|
| 308 |
def __hash__(self): |
| 309 |
return hash(str(self)) |
| 310 |
|
| 311 |
def __eq__(self, other): |
| 312 |
if isinstance(other, ExpressionField): |
| 313 |
return super().__eq__(other) |
| 314 |
return Eq(field=self, other=other) |
| 315 |
|
| 316 |
def __gt__(self, other): |
| 317 |
return GT(field=self, other=other) |
| 318 |
|
| 319 |
def __ge__(self, other): |
| 320 |
return GTE(field=self, other=other) |
| 321 |
|
| 322 |
def __lt__(self, other): |
| 323 |
return LT(field=self, other=other) |
| 324 |
|
| 325 |
def __le__(self, other): |
| 326 |
return LTE(field=self, other=other) |
| 327 |
|
| 328 |
def __ne__(self, other): |
| 329 |
return NE(field=self, other=other) |
| 330 |
|
| 331 |
def __pos__(self): |
| 332 |
return self, SortDirection.ASCENDING |
| 333 |
|
| 334 |
def __neg__(self): |
| 335 |
return self, SortDirection.DESCENDING |
| 336 |
|
| 337 |
def __copy__(self): |
| 338 |
return self |
| 339 |
|
| 340 |
def __deepcopy__(self, memo): |
| 341 |
return self |
| 342 |
|
| 343 |
|
| 344 |
class DeleteRules(str, Enum): |
| 345 |
DO_NOTHING = "DO_NOTHING" |
| 346 |
DELETE_LINKS = "DELETE_LINKS" |
| 347 |
|
| 348 |
|
| 349 |
class WriteRules(str, Enum): |
| 350 |
DO_NOTHING = "DO_NOTHING" |
| 351 |
WRITE = "WRITE" |
| 352 |
|
| 353 |
|
| 354 |
class LinkTypes(str, Enum): |
| 355 |
DIRECT = "DIRECT" |
| 356 |
OPTIONAL_DIRECT = "OPTIONAL_DIRECT" |
| 357 |
LIST = "LIST" |
| 358 |
OPTIONAL_LIST = "OPTIONAL_LIST" |
| 359 |
|
| 360 |
BACK_DIRECT = "BACK_DIRECT" |
| 361 |
BACK_LIST = "BACK_LIST" |
| 362 |
OPTIONAL_BACK_DIRECT = "OPTIONAL_BACK_DIRECT" |
| 363 |
OPTIONAL_BACK_LIST = "OPTIONAL_BACK_LIST" |
| 364 |
|
| 365 |
|
| 366 |
class LinkInfo(BaseModel): |
| 367 |
field_name: str |
| 368 |
lookup_field_name: str |
| 369 |
document_class: type[BaseModel] # Document class |
| 370 |
link_type: LinkTypes |
| 371 |
nested_links: dict | None = None |
| 372 |
is_fetchable: bool = True |
| 373 |
|
| 374 |
|
| 375 |
T = TypeVar("T") |
| 376 |
|
| 377 |
|
| 378 |
class Link(Generic[T]): |
| 379 |
def __init__(self, ref: DBRef, document_class: type[T]): |
| 380 |
self.ref = ref |
| 381 |
self.document_class = document_class |
| 382 |
|
| 383 |
async def fetch(self, fetch_links: bool = False) -> "T | Link[T]": |
| 384 |
result = await self.document_class.get( # type: ignore |
| 385 |
self.ref.id, with_children=True, fetch_links=fetch_links |
| 386 |
) |
| 387 |
return result or self |
| 388 |
|
| 389 |
@classmethod |
| 390 |
async def fetch_one(cls, link: "Link[T]"): |
| 391 |
return await link.fetch() |
| 392 |
|
| 393 |
@classmethod |
| 394 |
async def fetch_list( |
| 395 |
cls, |
| 396 |
links: list["Link[T] | DocType"], |
| 397 |
fetch_links: bool = False, |
| 398 |
): |
| 399 |
""" |
| 400 |
Fetch list that contains links and documents |
| 401 |
:param links: |
| 402 |
:param fetch_links: |
| 403 |
:return: |
| 404 |
""" |
| 405 |
data = Link.repack_links(links) # type: ignore |
| 406 |
ids_to_fetch = [] |
| 407 |
document_class = None |
| 408 |
for _doc_id, link in data.items(): |
| 409 |
if isinstance(link, Link): |
| 410 |
if document_class is None: |
| 411 |
document_class = link.document_class |
| 412 |
else: |
| 413 |
if document_class != link.document_class: |
| 414 |
raise ValueError( |
| 415 |
"All the links must have the same model class" |
| 416 |
) |
| 417 |
ids_to_fetch.append(link.ref.id) |
| 418 |
|
| 419 |
if ids_to_fetch: |
| 420 |
fetched_models = await document_class.find( # type: ignore |
| 421 |
In("_id", ids_to_fetch), |
| 422 |
with_children=True, |
| 423 |
fetch_links=fetch_links, |
| 424 |
).to_list() |
| 425 |
|
| 426 |
for model in fetched_models: |
| 427 |
data[model.id] = model |
| 428 |
|
| 429 |
return list(data.values()) |
| 430 |
|
| 431 |
@staticmethod |
| 432 |
def repack_links( |
| 433 |
links: list["Link[T] | DocType"], |
| 434 |
) -> OrderedDict[Any, Any]: |
| 435 |
result = OrderedDict() |
| 436 |
for link in links: |
| 437 |
if isinstance(link, Link): |
| 438 |
result[link.ref.id] = link |
| 439 |
else: |
| 440 |
result[link.id] = link |
| 441 |
return result |
| 442 |
|
| 443 |
@classmethod |
| 444 |
async def fetch_many(cls, links: list["Link[T]"]) -> list["T | Link[T]"]: |
| 445 |
coros = [] |
| 446 |
for link in links: |
| 447 |
coros.append(link.fetch()) |
| 448 |
return await asyncio.gather(*coros) |
| 449 |
|
| 450 |
@staticmethod |
| 451 |
def serialize(value: "Link[T] | BaseModel"): |
| 452 |
if isinstance(value, Link): |
| 453 |
return value.to_dict() |
| 454 |
return value.model_dump(mode="json") |
| 455 |
|
| 456 |
@classmethod |
| 457 |
def wrapped_validate( |
| 458 |
cls, source_type: type[Any], handler: GetCoreSchemaHandler |
| 459 |
): |
| 460 |
def validate( |
| 461 |
v: "Link[T] | T | DBRef | dict[str, Any]", |
| 462 |
validation_info: ValidationInfo, |
| 463 |
) -> "Link[T] | T": |
| 464 |
document_class = DocsRegistry.evaluate_fr( # type: ignore |
| 465 |
get_args(source_type)[0] |
| 466 |
) |
| 467 |
|
| 468 |
if isinstance(v, DBRef): |
| 469 |
return cls(ref=v, document_class=document_class) |
| 470 |
if isinstance(v, Link): |
| 471 |
return v |
| 472 |
if isinstance(v, dict) and v.keys() == {"id", "collection"}: |
| 473 |
return cls( |
| 474 |
ref=DBRef( |
| 475 |
collection=v["collection"], |
| 476 |
id=TypeAdapter( |
| 477 |
document_class.model_fields["id"].annotation |
| 478 |
).validate_python(v["id"]), |
| 479 |
), |
| 480 |
document_class=document_class, |
| 481 |
) |
| 482 |
if isinstance(v, (dict, BaseModel)): |
| 483 |
return parse_obj(document_class, v) |
| 484 |
|
| 485 |
# Default fallback case for unknown type |
| 486 |
new_id = TypeAdapter( |
| 487 |
document_class.model_fields["id"].annotation |
| 488 |
).validate_python(v) |
| 489 |
ref = DBRef( |
| 490 |
collection=document_class.get_collection_name(), id=new_id |
| 491 |
) |
| 492 |
return cls(ref=ref, document_class=document_class) |
| 493 |
|
| 494 |
return validate |
| 495 |
|
| 496 |
@classmethod |
| 497 |
def __get_pydantic_core_schema__( |
| 498 |
cls, source_type: type[Any], handler: GetCoreSchemaHandler |
| 499 |
) -> CoreSchema: |
| 500 |
return core_schema.json_or_python_schema( |
| 501 |
python_schema=core_schema.with_info_plain_validator_function( |
| 502 |
cls.wrapped_validate(source_type, handler) |
| 503 |
), |
| 504 |
json_schema=core_schema.union_schema( |
| 505 |
[ |
| 506 |
core_schema.typed_dict_schema( |
| 507 |
{ |
| 508 |
"id": core_schema.typed_dict_field( |
| 509 |
core_schema.str_schema() |
| 510 |
), |
| 511 |
"collection": core_schema.typed_dict_field( |
| 512 |
core_schema.str_schema() |
| 513 |
), |
| 514 |
} |
| 515 |
), |
| 516 |
core_schema.dict_schema( |
| 517 |
keys_schema=core_schema.str_schema(), |
| 518 |
values_schema=core_schema.any_schema(), |
| 519 |
), |
| 520 |
] |
| 521 |
), |
| 522 |
serialization=core_schema.plain_serializer_function_ser_schema( |
| 523 |
function=lambda instance: cls.serialize(instance), |
| 524 |
when_used="json-unless-none", |
| 525 |
), |
| 526 |
) |
| 527 |
|
| 528 |
def to_ref(self): |
| 529 |
return self.ref |
| 530 |
|
| 531 |
def to_dict(self): |
| 532 |
return {"id": str(self.ref.id), "collection": self.ref.collection} |
| 533 |
|
| 534 |
|
| 535 |
class BackLink(Generic[T]): |
| 536 |
"""Back reference to a document""" |
| 537 |
|
| 538 |
def __init__(self, document_class: type[T]): |
| 539 |
self.document_class = document_class |
| 540 |
|
| 541 |
@classmethod |
| 542 |
def wrapped_validate( |
| 543 |
cls, source_type: type[Any], handler: GetCoreSchemaHandler |
| 544 |
): |
| 545 |
def validate( |
| 546 |
v: T | dict[str, Any], validation_info: ValidationInfo |
| 547 |
) -> "BackLink[T] | T": |
| 548 |
document_class = DocsRegistry.evaluate_fr( # type: ignore |
| 549 |
get_args(source_type)[0] |
| 550 |
) |
| 551 |
if isinstance(v, (dict, BaseModel)): |
| 552 |
return parse_obj(document_class, v) |
| 553 |
return cls(document_class=document_class) |
| 554 |
|
| 555 |
return validate |
| 556 |
|
| 557 |
@classmethod |
| 558 |
def __get_pydantic_core_schema__( |
| 559 |
cls, source_type: type[Any], handler: GetCoreSchemaHandler |
| 560 |
) -> CoreSchema: |
| 561 |
# NOTE: BackLinks are only virtual fields, they shouldn't be serialized nor appear in the schema. |
| 562 |
return core_schema.json_or_python_schema( |
| 563 |
python_schema=core_schema.with_info_plain_validator_function( |
| 564 |
cls.wrapped_validate(source_type, handler) |
| 565 |
), |
| 566 |
json_schema=core_schema.dict_schema( |
| 567 |
keys_schema=core_schema.str_schema(), |
| 568 |
values_schema=core_schema.any_schema(), |
| 569 |
), |
| 570 |
serialization=core_schema.plain_serializer_function_ser_schema( |
| 571 |
lambda instance: cls.to_dict(instance), |
| 572 |
return_schema=core_schema.dict_schema(), |
| 573 |
when_used="json-unless-none", |
| 574 |
), |
| 575 |
) |
| 576 |
|
| 577 |
def to_dict(self) -> dict[str, str]: |
| 578 |
document_class = DocsRegistry.evaluate_fr( |
| 579 |
getattr(self, "document_class", self.__class__) |
| 580 |
) |
| 581 |
return {"collection": document_class.get_collection_name()} |
| 582 |
|
| 583 |
|
| 584 |
class IndexModelField: |
| 585 |
def __init__(self, index: IndexModel): |
| 586 |
self.index = index |
| 587 |
self.name = index.document["name"] |
| 588 |
|
| 589 |
self.fields = tuple(sorted(self.index.document["key"])) |
| 590 |
self.options = tuple( |
| 591 |
sorted( |
| 592 |
(k, v) |
| 593 |
for k, v in self.index.document.items() |
| 594 |
if k not in ["key", "v"] |
| 595 |
) |
| 596 |
) |
| 597 |
|
| 598 |
def __eq__(self, other): |
| 599 |
return self.fields == other.fields and self.options == other.options |
| 600 |
|
| 601 |
def __repr__(self): |
| 602 |
return f"IndexModelField({self.name}, {self.fields}, {self.options})" |
| 603 |
|
| 604 |
@staticmethod |
| 605 |
def list_difference( |
| 606 |
left: list["IndexModelField"], right: list["IndexModelField"] |
| 607 |
): |
| 608 |
result = [] |
| 609 |
for index in left: |
| 610 |
if index not in right: |
| 611 |
result.append(index) |
| 612 |
return result |
| 613 |
|
| 614 |
@staticmethod |
| 615 |
def list_to_index_model(left: list["IndexModelField"]): |
| 616 |
return [index.index for index in left] |
| 617 |
|
| 618 |
@classmethod |
| 619 |
def from_pymongo_index_information(cls, index_info: dict): |
| 620 |
result = [] |
| 621 |
for name, details in index_info.items(): |
| 622 |
fields = details["key"] |
| 623 |
if ("_id", 1) in fields: |
| 624 |
continue |
| 625 |
|
| 626 |
options = {k: v for k, v in details.items() if k != "key"} |
| 627 |
index_model = IndexModelField( |
| 628 |
IndexModel(fields, name=name, **options) |
| 629 |
) |
| 630 |
result.append(index_model) |
| 631 |
return result |
| 632 |
|
| 633 |
def same_fields(self, other: "IndexModelField"): |
| 634 |
return self.fields == other.fields |
| 635 |
|
| 636 |
@staticmethod |
| 637 |
def find_index_with_the_same_fields( |
| 638 |
indexes: list["IndexModelField"], index: "IndexModelField" |
| 639 |
): |
| 640 |
for i in indexes: |
| 641 |
if i.same_fields(index): |
| 642 |
return i |
| 643 |
return None |
| 644 |
|
| 645 |
@staticmethod |
| 646 |
def merge_indexes( |
| 647 |
left: list["IndexModelField"], right: list["IndexModelField"] |
| 648 |
): |
| 649 |
left_dict = {index.fields: index for index in left} |
| 650 |
right_dict = {index.fields: index for index in right} |
| 651 |
left_dict.update(right_dict) |
| 652 |
return list(left_dict.values()) |
| 653 |
|
| 654 |
@classmethod |
| 655 |
def _validate(cls, v: Any) -> "IndexModelField": |
| 656 |
if isinstance(v, IndexModel): |
| 657 |
return IndexModelField(v) |
| 658 |
else: |
| 659 |
return IndexModelField(IndexModel(v)) |
| 660 |
|
| 661 |
@classmethod |
| 662 |
def __get_pydantic_core_schema__( |
| 663 |
cls, source_type: type[Any], handler: GetCoreSchemaHandler |
| 664 |
) -> CoreSchema: |
| 665 |
return core_schema.no_info_plain_validator_function(cls._validate) |