Skip to content

utils

SliceBounds dataclass

Normalized pagination parameters produced by :func:normalize_slice.

reverse=True signals that the ORDER BY directions should be flipped at query build time and the fetched list reversed in memory so the caller still sees rows in the original ordering. This is how negative indices and negative slice bounds are emulated without a COUNT(*) round-trip.

Attributes:

Name Type Description
limit Optional[int]

row count for LIMIT; None means "no limit"

offset int

row count for OFFSET; always non-negative

reverse bool

whether the query ordering must be flipped and the result list reversed in memory

Source code in ormar/queryset/utils.py
Python
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
@dataclass(frozen=True)
class SliceBounds:
    """
    Normalized pagination parameters produced by :func:`normalize_slice`.

    ``reverse=True`` signals that the ORDER BY directions should be flipped
    at query build time and the fetched list reversed in memory so the
    caller still sees rows in the original ordering. This is how negative
    indices and negative slice bounds are emulated without a ``COUNT(*)``
    round-trip.

    :ivar limit: row count for ``LIMIT``; ``None`` means "no limit"
    :vartype limit: Optional[int]
    :ivar offset: row count for ``OFFSET``; always non-negative
    :vartype offset: int
    :ivar reverse: whether the query ordering must be flipped and the
        result list reversed in memory
    :vartype reverse: bool
    """

    limit: Optional[int]
    offset: int
    reverse: bool

build_flatten_map(paths)

Build a nested-Ellipsis dict from pre-split flatten path tuples — the runtime representation threaded through model_dump recursion.

Example::

Text Only
1
2
3
4
5
6
7
8
9
paths = [
    ("author", "name"),
    ("author", "email"),
    ("category", "title"),
]
build_flatten_map(paths) == {
    "author": {"name": ..., "email": ...},
    "category": {"title": ...},
}

Parameters:

Name Type Description Default
paths Iterable[PathParts]

iterable of tuple paths (each path already split on __)

required

Returns:

Type Description
dict

nested dict where leaves are ...

Source code in ormar/queryset/utils.py
Python
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
def build_flatten_map(paths: Iterable[PathParts]) -> dict:
    """
    Build a nested-Ellipsis dict from pre-split flatten path tuples — the
    runtime representation threaded through ``model_dump`` recursion.

    Example::

        paths = [
            ("author", "name"),
            ("author", "email"),
            ("category", "title"),
        ]
        build_flatten_map(paths) == {
            "author": {"name": ..., "email": ...},
            "category": {"title": ...},
        }

    :param paths: iterable of tuple paths (each path already split on ``__``)
    :type paths: Iterable[PathParts]
    :return: nested dict where leaves are ``...``
    :rtype: dict
    """
    result: dict = {}
    for parts in paths:
        current = result
        last = len(parts) - 1
        for i, part in enumerate(parts):
            if i == last:
                current[part] = ...
            else:
                current = current.setdefault(part, {})
    return result

convert_set_to_required_dict(set_to_convert)

Converts set to dictionary of required keys. Required key is Ellipsis.

Parameters:

Name Type Description Default
set_to_convert set

set to convert to dict

required

Returns:

Type Description
dict

set converted to dict of ellipsis

Source code in ormar/queryset/utils.py
Python
359
360
361
362
363
364
365
366
367
368
369
370
371
372
def convert_set_to_required_dict(set_to_convert: set) -> dict:
    """
    Converts set to dictionary of required keys.
    Required key is Ellipsis.

    :param set_to_convert: set to convert to dict
    :type set_to_convert: set
    :return: set converted to dict of ellipsis
    :rtype: dict
    """
    new_dict = dict()
    for key in set_to_convert:
        new_dict[key] = Ellipsis
    return new_dict

extract_access_chains(value)

Unwrap FieldAccessor inputs (or lists that contain them) into their underlying dunder-path strings so downstream parsers see a uniform shape. Anything that isn't an accessor (or list of accessors) is returned unchanged — sets, tuples, dicts, and plain strings all pass through.

Parameters:

Name Type Description Default
value Any

user input for a relation-spec method (select_related, prefetch_related, flatten_fields)

required

Returns:

Type Description
Any

a dunder string, a list with each accessor replaced by its chain, or the original value unchanged

Source code in ormar/queryset/utils.py
Python
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
def extract_access_chains(value: Any) -> Any:
    """
    Unwrap ``FieldAccessor`` inputs (or lists that contain them) into their
    underlying dunder-path strings so downstream parsers see a uniform shape.
    Anything that isn't an accessor (or list of accessors) is returned
    unchanged — sets, tuples, dicts, and plain strings all pass through.

    :param value: user input for a relation-spec method (``select_related``,
        ``prefetch_related``, ``flatten_fields``)
    :type value: Any
    :return: a dunder string, a list with each accessor replaced by its chain,
        or the original value unchanged
    :rtype: Any
    """
    # Late import to avoid circular dependency with queryset package.
    from ormar.queryset.field_accessor import FieldAccessor

    if isinstance(value, FieldAccessor):
        return [value._access_chain]
    if isinstance(value, list):
        return [
            item._access_chain if isinstance(item, FieldAccessor) else item
            for item in value
        ]
    return value

get_or_create_with_retry(database, get, create) async

Shared body of get_or_create for querysets and relation proxies.

On IntegrityError from create the get is retried once and the error re-raised if it still finds nothing. Inside a transaction create runs in a savepoint, serialised per transaction connection because releasing a savepoint releases the ones opened after it; nested calls in the same task (e.g. from a pre_save signal) reuse the held lock.

Parameters:

Name Type Description Default
database DatabaseConnection

database the model belongs to

required
get Callable[[], Awaitable[T]]

coroutine factory looking up the row

required
create Callable[[], Awaitable[T]]

coroutine factory creating the row

required

Returns:

Type Description
tuple[T, bool]

model instance and whether it was created

Source code in ormar/queryset/utils.py
Python
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
async def get_or_create_with_retry(
    database: "DatabaseConnection",
    get: Callable[[], Awaitable[T]],
    create: Callable[[], Awaitable[T]],
) -> tuple[T, bool]:
    """
    Shared body of ``get_or_create`` for querysets and relation proxies.

    On ``IntegrityError`` from ``create`` the ``get`` is retried once and the
    error re-raised if it still finds nothing. Inside a transaction ``create``
    runs in a savepoint, serialised per transaction connection because
    releasing a savepoint releases the ones opened after it; nested calls in
    the same task (e.g. from a ``pre_save`` signal) reuse the held lock.

    :param database: database the model belongs to
    :type database: DatabaseConnection
    :param get: coroutine factory looking up the row
    :type get: Callable[[], Awaitable[T]]
    :param create: coroutine factory creating the row
    :type create: Callable[[], Awaitable[T]]
    :return: model instance and whether it was created
    :rtype: tuple[T, bool]
    """
    try:
        return await get(), False
    except NoMatch:
        pass
    connection = database.get_transaction_connection()
    try:
        if connection is None:
            return await create(), True
        lock = savepoint_locks.setdefault(connection, asyncio.Lock())
        async with nullcontext() if holds_savepoint_lock.get() else lock:
            token = holds_savepoint_lock.set(True)
            try:
                async with database.transaction():
                    return await create(), True
            finally:
                holds_savepoint_lock.reset(token)
    except sqlalchemy.exc.IntegrityError as integrity_error:
        try:
            return await get(), False
        except NoMatch:
            raise integrity_error from None

get_relationship_alias_model_and_str(source_model, related_parts)

Walks the relation to retrieve the actual model on which the clause should be constructed and the alias of the table under which that model is joined.

The alias is derived from the path of the joined table, which for through models is the path of the many to many relation followed by the through model name - also when the relation itself was omitted in the related parts.

Note that through model names are removed from passed related_parts, or replaced with the many to many relation they belong to if it was omitted, so that the relation string joins the through model.

Parameters:

Name Type Description Default
related_parts list

list of related names extracted from string

required
source_model type[Model]

model from which relation starts

required

Returns:

Type Description
tuple[str, type["Model"], str, bool]

table prefix, target model, relation string and is through flag

Source code in ormar/queryset/utils.py
Python
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
def get_relationship_alias_model_and_str(
    source_model: type["Model"], related_parts: list
) -> tuple[str, type["Model"], str, bool]:
    """
    Walks the relation to retrieve the actual model on which the clause should be
    constructed and the alias of the table under which that model is joined.

    The alias is derived from the path of the joined table, which for through
    models is the path of the many to many relation followed by the through model
    name - also when the relation itself was omitted in the related parts.

    Note that through model names are removed from passed related_parts, or
    replaced with the many to many relation they belong to if it was omitted, so
    that the relation string joins the through model.

    :param related_parts: list of related names extracted from string
    :type related_parts: Union[list, list[str]]
    :param source_model: model from which relation starts
    :type source_model: type[Model]
    :return: table prefix, target model, relation string and is through flag
    :rtype: tuple[str, type["Model"], str, bool]
    """
    is_through = False
    target_model = source_model
    previous_models = [target_model]
    table_path_parts: list[str] = []
    for relation in related_parts[:]:
        related_field = target_model.ormar_config.model_fields[relation]
        if related_field.is_through:
            is_through = True
            implicit_relation = resolve_implicit_through_relation(
                related_parts=related_parts,
                relation=relation,
                related_field=related_field,
                previous_models=previous_models,
            )
            if implicit_relation:
                table_path_parts.append(implicit_relation)
        table_path_parts.append(relation)
        target_model = related_field.to
        if not is_through:
            previous_models.append(target_model)
    relation_str = "__".join(related_parts)
    table_prefix = alias_for("__".join(table_path_parts))
    return table_prefix, target_model, relation_str, is_through

normalize_slice(key)

Top-level dispatcher: turns a Python integer index or slice into a :class:SliceBounds suitable for QuerySet.

Delegates to a dedicated helper for each shape. Any shape that would require a COUNT(*) round-trip (step != 1, a bare [:-N], or mixed-sign bounds) raises QueryDefinitionError.

Examples::

Text Only
1
2
3
5           → SliceBounds(limit=1, offset=5,  reverse=False)
slice(2, 8) → SliceBounds(limit=6, offset=2,  reverse=False)
slice(-3, None) → SliceBounds(limit=3, offset=0, reverse=True)

Parameters:

Name Type Description Default
key Union[int, slice]

integer or slice passed to QuerySet.__getitem__

required

Returns:

Type Description
SliceBounds

normalized slice parameters

Source code in ormar/queryset/utils.py
Python
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
def normalize_slice(key: Union[int, slice]) -> SliceBounds:
    """
    Top-level dispatcher: turns a Python integer index or slice into a
    :class:`SliceBounds` suitable for ``QuerySet``.

    Delegates to a dedicated helper for each shape. Any shape that would
    require a ``COUNT(*)`` round-trip (``step != 1``, a bare ``[:-N]``, or
    mixed-sign bounds) raises ``QueryDefinitionError``.

    Examples::

        5           → SliceBounds(limit=1, offset=5,  reverse=False)
        slice(2, 8) → SliceBounds(limit=6, offset=2,  reverse=False)
        slice(-3, None) → SliceBounds(limit=3, offset=0, reverse=True)

    :param key: integer or slice passed to ``QuerySet.__getitem__``
    :type key: int | slice
    :return: normalized slice parameters
    :rtype: SliceBounds
    """
    if isinstance(key, int):
        return _int_to_limit_offset(key)
    if isinstance(key, slice):
        return _slice_to_limit_offset(key)
    raise QueryDefinitionError(
        f"QuerySet indices must be integers or slices, not {type(key).__name__}."
    )

resolve_implicit_through_relation(related_parts, relation, related_field, previous_models)

Removes the through model name from related parts, or replaces it with the name of the many to many relation the through model belongs to and returns that name, if the relation was not part of the path (i.e. postcategory__sort_order used from Post).

Parameters:

Name Type Description Default
related_parts list

split relation string, through name is removed or replaced in place

required
relation str

name of the through field

required
related_field BaseField

through field

required
previous_models list[type[Model]]

already visited models in relation chain

required

Returns:

Type Description
Optional[str]

name of the omitted many to many relation or None if it was in the path

Source code in ormar/queryset/utils.py
Python
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
def resolve_implicit_through_relation(
    related_parts: list,
    relation: str,
    related_field: "BaseField",
    previous_models: list[type["Model"]],
) -> Optional[str]:
    """
    Removes the through model name from related parts, or replaces it with the
    name of the many to many relation the through model belongs to and returns
    that name, if the relation was not part of the path
    (i.e. ``postcategory__sort_order`` used from ``Post``).

    :param related_parts: split relation string, through name is removed or
        replaced in place
    :type related_parts: list[str]
    :param relation: name of the through field
    :type relation: str
    :param related_field: through field
    :type related_field: BaseField
    :param previous_models: already visited models in relation chain
    :type previous_models: list[type["Model"]]
    :return: name of the omitted many to many relation or None if it was in the path
    :rtype: Optional[str]
    """
    through_index = related_parts.index(relation)
    relation_name = related_field.related_name or ""
    through_field = related_field.owner.ormar_config.model_fields[relation_name]
    if len(previous_models) > 1 and previous_models[-2] == through_field.to:
        del related_parts[through_index]
        return None
    related_parts[through_index] = relation_name
    return relation_name

subtract_dict(current_dict, updating_dict)

Subtract one dict from another with regard for nested keys.

That way nested sets are differenced, nested dicts subtracted and keys left empty removed. Returns a new dict and leaves current_dict (and the dicts nested in it) unchanged, so it can be a shared cached map::

Text Only
1
2
subtract_dict({"a": {"b": ..., "c": ...}}, {"a": {"b": ...}})
# -> {"a": {"c": ...}}

Parameters:

Name Type Description Default
current_dict Any

dict to subtract from

required
updating_dict Any

dict with values to subtract

required

Returns:

Type Description
dict

current_dict without the values of updating_dict

Source code in ormar/queryset/utils.py
Python
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
def subtract_dict(current_dict: Any, updating_dict: Any) -> dict:  # noqa: CCR001
    """
    Subtract one dict from another with regard for nested keys.

    That way nested sets are differenced, nested dicts subtracted and keys
    left empty removed. Returns a new dict and leaves ``current_dict`` (and
    the dicts nested in it) unchanged, so it can be a shared cached map::

        subtract_dict({"a": {"b": ..., "c": ...}}, {"a": {"b": ...}})
        # -> {"a": {"c": ...}}

    :param current_dict: dict to subtract from
    :type current_dict: dict[str, ellipsis]
    :param updating_dict: dict with values to subtract
    :type updating_dict: dict
    :return: current_dict without the values of updating_dict
    :rtype: dict
    """
    current_dict = dict(current_dict.items())
    for key, value in updating_dict.items():
        old_key = current_dict.get(key, {})
        new_value: Optional[Union[dict, set]] = None
        if not old_key:
            continue
        if isinstance(value, set) and isinstance(old_key, set):
            new_value = old_key.difference(value)
        elif isinstance(value, (set, collections.abc.Mapping)) and isinstance(
            old_key, (set, collections.abc.Mapping)
        ):
            value = (
                convert_set_to_required_dict(value)
                if not isinstance(value, collections.abc.Mapping)
                else value
            )
            old_key = (
                convert_set_to_required_dict(old_key)
                if not isinstance(old_key, collections.abc.Mapping)
                else old_key
            )
            new_value = subtract_dict(old_key, value)

        if new_value:
            current_dict[key] = new_value
        else:
            current_dict.pop(key, None)
    return current_dict

translate_list_to_dict(list_to_trans, default=...)

Splits the list of strings by '__' and converts them to dictionary with nested models grouped by parent model. That way each model appears only once in the whole dictionary and children are grouped under parent name.

Default required key ise Ellipsis like in pydantic.

Parameters:

Name Type Description Default
list_to_trans Union[list, set]

input list

required
default Any

value to use as a default value

...

Returns:

Type Description
dict

converted to dictionary input list

Source code in ormar/queryset/utils.py
Python
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
def translate_list_to_dict(  # noqa: CCR001
    list_to_trans: Union[list, set], default: Any = ...
) -> dict:
    """
    Splits the list of strings by '__' and converts them to dictionary with nested
    models grouped by parent model. That way each model appears only once in the whole
    dictionary and children are grouped under parent name.

    Default required key ise Ellipsis like in pydantic.

    :param list_to_trans: input list
    :type list_to_trans: Union[list, set]
    :param default: value to use as a default value
    :type default: Any
    :return: converted to dictionary input list
    :rtype: dict
    """
    return ormar_rust_utils.translate_list_to_dict(list(list_to_trans), default)

update(current_dict, updating_dict)

Update one dict with another but with regard for nested keys.

That way nested sets are unionised, dicts updated and only other values are overwritten.

Parameters:

Name Type Description Default
current_dict Any

dict to update

required
updating_dict Any

dict with values to update

required

Returns:

Type Description
dict

combination of both dicts

Source code in ormar/queryset/utils.py
Python
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
def update(current_dict: Any, updating_dict: Any) -> dict:  # noqa: CCR001
    """
    Update one dict with another but with regard for nested keys.

    That way nested sets are unionised, dicts updated and
    only other values are overwritten.

    :param current_dict: dict to update
    :type current_dict: dict[str, ellipsis]
    :param updating_dict: dict with values to update
    :type updating_dict: dict
    :return: combination of both dicts
    :rtype: dict
    """
    if current_dict is Ellipsis:
        current_dict = dict()
    for key, value in updating_dict.items():
        if isinstance(value, collections.abc.Mapping):
            old_key = current_dict.get(key, {})
            if isinstance(old_key, set):
                old_key = convert_set_to_required_dict(old_key)
            current_dict[key] = update(old_key, value)
        elif isinstance(value, set) and isinstance(current_dict.get(key), set):
            current_dict[key] = current_dict.get(key).union(value)
        else:
            current_dict[key] = value
    return current_dict

update_dict_from_list(curr_dict, list_to_update)

Converts the list into dictionary and later performs special update, where nested keys that are sets or dicts are combined and not overwritten.

Parameters:

Name Type Description Default
curr_dict dict

dict to update

required
list_to_update Union[list, set]

list with values to update the dict

required

Returns:

Type Description
dict

updated dict

Source code in ormar/queryset/utils.py
Python
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
def update_dict_from_list(curr_dict: dict, list_to_update: Union[list, set]) -> dict:
    """
    Converts the list into dictionary and later performs special update, where
    nested keys that are sets or dicts are combined and not overwritten.

    :param curr_dict: dict to update
    :type curr_dict: dict
    :param list_to_update: list with values to update the dict
    :type list_to_update: list[str]
    :return: updated dict
    :rtype: dict
    """
    updated_dict = copy.copy(curr_dict)
    dict_to_update = translate_list_to_dict(list_to_update)
    update(updated_dict, dict_to_update)
    return updated_dict