Skip to content

queries

FilterQuery

Modifies the select query with given list of where/filter clauses.

With a binder (see templates.SlotBinder) the filter values become named bind parameters, so the built select can be cached as a statement template and run again with other values.

Source code in ormar/queryset/queries/filter_query.py
Python
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class FilterQuery:
    """
    Modifies the select query with given list of where/filter clauses.

    With a ``binder`` (see ``templates.SlotBinder``) the filter values become
    named bind parameters, so the built select can be cached as a statement
    template and run again with other values.
    """

    def __init__(
        self,
        filter_clauses: list[FilterAction],
        exclude: bool = False,
        binder: Optional["SlotBinder"] = None,
    ) -> None:
        self.exclude = exclude
        self.filter_clauses = filter_clauses
        self.binder = binder

    def apply(
        self,
        expr: Select[Any],
    ) -> Select[Any]:
        """
        Applies all filter clauses if set.

        :param expr: query to modify
        :type expr: sqlalchemy.sql.selectable.Select
        :return: modified query
        :rtype: sqlalchemy.sql.selectable.Select
        """
        if self.filter_clauses:
            clauses: list[Union[TextClause, ColumnElement[Any]]] = [
                x.get_text_clause(binder=self.binder) for x in self.filter_clauses
            ]
            if self.exclude:
                # every exclude() call is negated on its own, all of them are ANDed
                clauses = [sqlalchemy.sql.not_(x) for x in clauses]
            clause: Union[TextClause, ColumnElement[Any]] = (
                clauses[0] if len(clauses) == 1 else sqlalchemy.sql.and_(*clauses)
            )
            expr = expr.where(clause)
        return expr

apply(expr)

Applies all filter clauses if set.

Parameters:

Name Type Description Default
expr Select[Any]

query to modify

required

Returns:

Type Description
sqlalchemy.sql.selectable.Select

modified query

Source code in ormar/queryset/queries/filter_query.py
Python
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def apply(
    self,
    expr: Select[Any],
) -> Select[Any]:
    """
    Applies all filter clauses if set.

    :param expr: query to modify
    :type expr: sqlalchemy.sql.selectable.Select
    :return: modified query
    :rtype: sqlalchemy.sql.selectable.Select
    """
    if self.filter_clauses:
        clauses: list[Union[TextClause, ColumnElement[Any]]] = [
            x.get_text_clause(binder=self.binder) for x in self.filter_clauses
        ]
        if self.exclude:
            # every exclude() call is negated on its own, all of them are ANDed
            clauses = [sqlalchemy.sql.not_(x) for x in clauses]
        clause: Union[TextClause, ColumnElement[Any]] = (
            clauses[0] if len(clauses) == 1 else sqlalchemy.sql.and_(*clauses)
        )
        expr = expr.where(clause)
    return expr

LimitQuery

Modifies the select query with limit clause.

With a binder (see templates.SlotBinder) the limit is bound as :ormar_limit, so one cached statement serves every limit value.

Source code in ormar/queryset/queries/limit_query.py
Python
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class LimitQuery:
    """
    Modifies the select query with limit clause.

    With a ``binder`` (see ``templates.SlotBinder``) the limit is bound as
    ``:ormar_limit``, so one cached statement serves every limit value.
    """

    def __init__(
        self, limit_count: Optional[int], binder: Optional["SlotBinder"] = None
    ) -> None:
        self.limit_count = limit_count
        self.binder = binder

    def apply(self, expr: sqlalchemy.sql.Select) -> sqlalchemy.sql.Select:
        """
        Applies the limit clause.

        :param expr: query to modify
        :type expr: sqlalchemy.sql.selectable.Select
        :return: modified query
        :rtype: sqlalchemy.sql.selectable.Select
        """

        if self.limit_count is not None:
            value = (
                self.binder.limit(value=self.limit_count)
                if self.binder is not None
                else self.limit_count
            )
            expr = expr.limit(limit=value)

        return expr

apply(expr)

Applies the limit clause.

Parameters:

Name Type Description Default
expr Select

query to modify

required

Returns:

Type Description
sqlalchemy.sql.selectable.Select

modified query

Source code in ormar/queryset/queries/limit_query.py
Python
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def apply(self, expr: sqlalchemy.sql.Select) -> sqlalchemy.sql.Select:
    """
    Applies the limit clause.

    :param expr: query to modify
    :type expr: sqlalchemy.sql.selectable.Select
    :return: modified query
    :rtype: sqlalchemy.sql.selectable.Select
    """

    if self.limit_count is not None:
        value = (
            self.binder.limit(value=self.limit_count)
            if self.binder is not None
            else self.limit_count
        )
        expr = expr.limit(limit=value)

    return expr

OffsetQuery

Modifies the select query with offset if set

With a binder (see templates.SlotBinder) the offset is bound as :ormar_offset, so one cached statement serves every non-zero offset.

Source code in ormar/queryset/queries/offset_query.py
Python
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class OffsetQuery:
    """
    Modifies the select query with offset if set

    With a ``binder`` (see ``templates.SlotBinder``) the offset is bound as
    ``:ormar_offset``, so one cached statement serves every non-zero offset.
    """

    def __init__(
        self, query_offset: Optional[int], binder: Optional["SlotBinder"] = None
    ) -> None:
        self.query_offset = query_offset
        self.binder = binder

    def apply(self, expr: sqlalchemy.sql.Select) -> sqlalchemy.sql.Select:
        """
        Applies the offset clause.

        :param expr: query to modify
        :type expr: sqlalchemy.sql.selectable.Select
        :return: modified query
        :rtype: sqlalchemy.sql.selectable.Select
        """
        if self.query_offset:
            value = (
                self.binder.offset(value=self.query_offset)
                if self.binder is not None
                else self.query_offset
            )
            expr = expr.offset(offset=value)
        return expr

apply(expr)

Applies the offset clause.

Parameters:

Name Type Description Default
expr Select

query to modify

required

Returns:

Type Description
sqlalchemy.sql.selectable.Select

modified query

Source code in ormar/queryset/queries/offset_query.py
Python
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def apply(self, expr: sqlalchemy.sql.Select) -> sqlalchemy.sql.Select:
    """
    Applies the offset clause.

    :param expr: query to modify
    :type expr: sqlalchemy.sql.selectable.Select
    :return: modified query
    :rtype: sqlalchemy.sql.selectable.Select
    """
    if self.query_offset:
        value = (
            self.binder.offset(value=self.query_offset)
            if self.binder is not None
            else self.query_offset
        )
        expr = expr.offset(offset=value)
    return expr

OrderQuery

Modifies the select query with given list of order_by clauses.

Source code in ormar/queryset/queries/order_query.py
Python
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class OrderQuery:
    """
    Modifies the select query with given list of order_by clauses.
    """

    def __init__(self, sorted_orders: dict) -> None:
        self.sorted_orders = sorted_orders

    def apply(self, expr: sqlalchemy.sql.Select) -> sqlalchemy.sql.Select:
        """
        Applies all order_by clauses if set.

        :param expr: query to modify
        :type expr: sqlalchemy.sql.selectable.Select
        :return: modified query
        :rtype: sqlalchemy.sql.selectable.Select
        """
        if self.sorted_orders:
            for order in list(self.sorted_orders.values()):
                if order is not None:
                    expr = expr.order_by(order)
        return expr

apply(expr)

Applies all order_by clauses if set.

Parameters:

Name Type Description Default
expr Select

query to modify

required

Returns:

Type Description
sqlalchemy.sql.selectable.Select

modified query

Source code in ormar/queryset/queries/order_query.py
Python
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def apply(self, expr: sqlalchemy.sql.Select) -> sqlalchemy.sql.Select:
    """
    Applies all order_by clauses if set.

    :param expr: query to modify
    :type expr: sqlalchemy.sql.selectable.Select
    :return: modified query
    :rtype: sqlalchemy.sql.selectable.Select
    """
    if self.sorted_orders:
        for order in list(self.sorted_orders.values()):
            if order is not None:
                expr = expr.order_by(order)
    return expr

PrefetchQuery

Query used to fetch related models in subsequent queries. Each model is fetched only ones by the name of the relation. That means that for each prefetch_related entry next query is issued to database.

Source code in ormar/queryset/queries/prefetch_query.py
Python
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
class PrefetchQuery:
    """
    Query used to fetch related models in subsequent queries.
    Each model is fetched only ones by the name of the relation.
    That means that for each prefetch_related entry next query is issued to database.
    """

    def __init__(  # noqa: CFQ002
        self,
        model_cls: type["Model"],
        excludable: "ExcludableItems",
        prefetch_related: list,
        select_related: list,
        orders_by: list["OrderAction"],
        prefetch_querysets: Optional[dict[str, "QuerySet"]] = None,
    ) -> None:
        self.model = model_cls
        self.prefetch_querysets = prefetch_querysets or {}
        # nodes add their own includes/excludes, keep the queryset's untouched
        self.excludable = ormar.ExcludableItems.from_excludable(excludable)
        self.select_dict = translate_list_to_dict(select_related, default={})
        self.prefetch_dict = translate_list_to_dict(prefetch_related, default={})
        self.orders_by = orders_by
        self.load_tasks: list[Node] = []

    async def prefetch_related(self, models: Sequence["Model"]) -> Sequence["Model"]:
        """
        Main entry point for prefetch_query.

        Receives list of already initialized parent models with all children from
        select_related already populated.

        Returns list with related models already prefetched and set.

        :param models: list of already instantiated models from main query
        :type models: Sequence[Model]
        :return: list of models with children prefetched
        :rtype: list[Model]
        """
        parent_task = RootNode(models=cast(list["Model"], models))
        self._build_load_tree(
            prefetch_dict=self.prefetch_dict,
            select_dict=self.select_dict,
            parent=parent_task,
            model=self.model,
            path="",
        )
        await parent_task.load_data()
        parent_task.reload_tree()
        return parent_task.models

    def _build_load_tree(
        self,
        select_dict: dict,
        prefetch_dict: dict,
        parent: Node,
        model: type["Model"],
        path: str,
    ) -> None:
        """
        Build a tree of already loaded nodes and nodes that need
        to be loaded through the prefetch query.

        :param select_dict: dictionary wth select query structure
        :type select_dict: dict
        :param prefetch_dict: dictionary with prefetch query structure
        :type prefetch_dict: dict
        :param parent: parent Node
        :type parent: Node
        :param model: currently processed model
        :type model: Model
        """
        for related in prefetch_dict.keys():
            relation_path = f"{path}__{related}" if path else related
            relation_field = cast(
                "ForeignKeyField", model.ormar_config.model_fields[related]
            )
            if related in select_dict:
                if relation_path in self.prefetch_querysets:
                    raise QueryDefinitionError(
                        f"Prefetch of {relation_path} cannot be combined with "
                        "select_related of the same relation."
                    )
                task: Node = AlreadyLoadedNode(
                    relation_field=relation_field, parent=parent
                )
            else:
                task = LoadNode(
                    relation_field=relation_field,
                    excludable=self.excludable,
                    orders_by=self.orders_by,
                    parent=parent,
                    source_model=self.model,
                    queryset=self.prefetch_querysets.get(relation_path),
                )
            if prefetch_dict:
                self._build_load_tree(
                    select_dict=select_dict.get(related, {}),
                    prefetch_dict=prefetch_dict.get(related, {}),
                    parent=task,
                    model=model.ormar_config.model_fields[related].to,
                    path=relation_path,
                )

Main entry point for prefetch_query.

Receives list of already initialized parent models with all children from select_related already populated.

Returns list with related models already prefetched and set.

Parameters:

Name Type Description Default
models Sequence[Model]

list of already instantiated models from main query

required

Returns:

Type Description
list[Model]

list of models with children prefetched

Source code in ormar/queryset/queries/prefetch_query.py
Python
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
async def prefetch_related(self, models: Sequence["Model"]) -> Sequence["Model"]:
    """
    Main entry point for prefetch_query.

    Receives list of already initialized parent models with all children from
    select_related already populated.

    Returns list with related models already prefetched and set.

    :param models: list of already instantiated models from main query
    :type models: Sequence[Model]
    :return: list of models with children prefetched
    :rtype: list[Model]
    """
    parent_task = RootNode(models=cast(list["Model"], models))
    self._build_load_tree(
        prefetch_dict=self.prefetch_dict,
        select_dict=self.select_dict,
        parent=parent_task,
        model=self.model,
        path="",
    )
    await parent_task.load_data()
    parent_task.reload_tree()
    return parent_task.models

Query

Builds the select of a queryset: joins of select_related, selected columns, filters, ordering, limit and offset (with a pagination subquery when a limit meets select_related).

With a binder (see templates.SlotBinder) every filter value, the limit and the offset are bound as named parameters, so the select can be cached as a statement template.

Source code in ormar/queryset/queries/query.py
Python
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
class Query:
    """
    Builds the select of a queryset: joins of ``select_related``, selected
    columns, filters, ordering, limit and offset (with a pagination subquery
    when a limit meets ``select_related``).

    With a ``binder`` (see ``templates.SlotBinder``) every filter value, the
    limit and the offset are bound as named parameters, so the select can be
    cached as a statement template.
    """

    def __init__(  # noqa CFQ002
        self,
        model_cls: type["Model"],
        filter_clauses: list[FilterAction],
        exclude_clauses: list[FilterAction],
        select_related: list,
        limit_count: Optional[int],
        offset: Optional[int],
        excludable: "ExcludableItems",
        order_bys: Optional[list["OrderAction"]],
        limit_raw_sql: bool,
        binder: Optional["SlotBinder"] = None,
    ) -> None:
        self.query_offset = offset
        self.limit_count = limit_count
        self._select_related = select_related[:]
        self.filter_clauses = filter_clauses[:]
        self.exclude_clauses = exclude_clauses[:]
        self.excludable = excludable

        self.model_cls = model_cls
        self.table = self.model_cls.ormar_config.table

        self.used_aliases: list[str] = []

        self.select_from: Union[Join, Table, list[str]] = []
        self.columns: list[Column] = []
        self.order_columns = order_bys
        self.sorted_orders: dict[OrderAction, TextClause] = {}
        self._init_sorted_orders()

        self.limit_raw_sql = limit_raw_sql
        self.binder = binder

    def _init_sorted_orders(self) -> None:
        """
        Initialize empty order_by dict to be populated later during the query call
        """
        if self.order_columns:
            for clause in self.order_columns:
                self.sorted_orders[clause] = None  # type: ignore

    def apply_order_bys_for_primary_model(self) -> None:  # noqa: CCR001
        """
        Applies order_by queries on main model when it's used as a subquery.
        That way the subquery with limit and offset only on main model has proper
        sorting applied and correct models are fetched.
        """
        current_table_sorted = False
        if self.order_columns:
            for clause in self.order_columns:
                if clause.is_source_model_order:
                    current_table_sorted = True
                    self.sorted_orders[clause] = clause.get_text_clause()

        if not current_table_sorted:
            self._apply_default_model_sorting()

    def _apply_default_model_sorting(self) -> None:
        """
        Applies orders_by from model OrmarConfig (if provided), if it was not provided
        it was filled by metaclass, so it's always there and falls back to pk column
        """
        for clause in ormar.OrderAction.from_model_defaults(self.model_cls):
            self.sorted_orders[clause] = clause.get_text_clause()

    def _pagination_query_required(self) -> bool:
        """
        Checks if limit or offset are set, the flag limit_sql_raw is not set
        and query has select_related applied. Otherwise we can limit/offset normally
        at the end of whole query.

        :return: result of the check
        :rtype: bool
        """
        return bool(
            (self.limit_count or self.query_offset)
            and not self.limit_raw_sql
            and self._select_related
        )

    def build_select_expression(self) -> sqlalchemy.sql.Select:
        """
        Main entry point from outside (after proper initialization).

        Extracts columns list to fetch,
        construct all required joins for select related,
        then applies all conditional and sort clauses.

        Returns ready to run query with all joins and clauses.

        :return: ready to run query with all joins and clauses.
        :rtype: sqlalchemy.sql.selectable.Select
        """
        self._join_related_models()

        if self._pagination_query_required():
            limit_qry, on_clause = self._build_pagination_condition()
            self.select_from = sqlalchemy.sql.join(
                cast("FromClauseRole", self.select_from), limit_qry, on_clause
            )

        expr = sqlalchemy.sql.select(*self.columns)
        expr = expr.select_from(cast("FromClauseRole", self.select_from))

        expr = self._apply_expression_modifiers(expr)

        # print("\n", expr.compile(compile_kwargs={"literal_binds": True}))
        self._reset_query_parameters()

        return expr

    def build_primary_key_select(self) -> sqlalchemy.sql.Select:
        """
        Select only the primary key of the rows the queryset matches, with the
        joins and filters of ``build_select_expression`` but no ordering, limit
        or offset. Updates and deletes filtering on related models restrict
        their rows to it::

            SELECT tracks.id FROM tracks
            LEFT OUTER JOIN albums AS t1b26c7_albums ON t1b26c7_albums.id = tracks.album
            WHERE t1b26c7_albums.name = :ormar_p0

        :return: select of the primary key columns
        :rtype: sqlalchemy.sql.selectable.Select
        """
        self._join_related_models()
        pk_columns = [
            self.table.c[alias]
            for alias in self.model_cls.ormar_config.pk.column_aliases()
        ]
        expr = sqlalchemy.sql.select(*pk_columns)
        expr = expr.select_from(cast("FromClauseRole", self.select_from))
        expr = self._apply_filters(expr)
        self._reset_query_parameters()
        return expr

    def _apply_filters(self, expr: sqlalchemy.sql.Select) -> sqlalchemy.sql.Select:
        """
        Apply the filter and the exclude clauses to a select.

        :param expr: select expression
        :type expr: sqlalchemy.sql.selectable.Select
        :return: filtered select
        :rtype: sqlalchemy.sql.selectable.Select
        """
        expr = FilterQuery(
            filter_clauses=self.filter_clauses, binder=self.binder
        ).apply(expr=expr)
        return FilterQuery(
            filter_clauses=self.exclude_clauses, exclude=True, binder=self.binder
        ).apply(expr=expr)

    def _join_related_models(self) -> None:
        """
        Set the own columns and default ordering of the main model, then join
        every ``select_related`` relation, extending ``select_from``, the
        selected columns and the orders.
        """
        self_related_fields = self.model_cls.own_table_columns(
            model=self.model_cls, excludable=self.excludable, use_alias=True
        )
        self.columns = prefixed_columns("", self.table, self_related_fields)  # type: ignore
        self.apply_order_bys_for_primary_model()
        self.select_from = self.table

        related_models = group_related_list(self._select_related)

        for related in related_models:
            remainder = None
            if isinstance(related_models, dict) and related_models[related]:
                remainder = related_models[related]
            sql_join = SqlJoin(
                used_aliases=self.used_aliases,
                select_from=self.select_from,  # type: ignore
                columns=self.columns,
                excludable=self.excludable,
                order_columns=self.order_columns,
                sorted_orders=self.sorted_orders,
                main_model=self.model_cls,
                relation_name=related,
                relation_str=related,
                related_models=remainder,
            )

            (
                self.used_aliases,
                self.select_from,
                self.columns,
                self.sorted_orders,
            ) = sql_join.build_join()  # type: ignore

    def _build_pagination_condition(
        self,
    ) -> tuple[
        sqlalchemy.sql.expression.TextClause, sqlalchemy.sql.expression.TextClause
    ]:
        """
        In order to apply limit and offset on main table in join only
        (otherwise you can get only partially constructed main model
        if number of children exceeds the applied limit and select_related is used)

        Used also to change first and get() without argument behaviour.
        Needed only if limit or offset are set, the flag limit_sql_raw is not set
        and query has select_related applied. Otherwise we can limit/offset normally
        at the end of whole query.

        The condition is added to filters to filter out desired number of main model
        primary key values. Whole query is used to determine the values.
        """
        pk_aliases = self.model_cls.ormar_config.pk.column_aliases()
        pk_aliased_names = tuple(f"{self.table.name}.{alias}" for alias in pk_aliases)
        qry_texts = [sqlalchemy.text(name) for name in pk_aliased_names]
        maxes = {}
        for order in list(self.sorted_orders.keys()):
            if (
                order is not None
                and order.get_field_name_text() not in pk_aliased_names
            ):
                aliased_col = order.get_field_name_text()
                maxes[aliased_col] = order.get_min_or_max()
            elif order.get_field_name_text() in pk_aliased_names:
                maxes[order.get_field_name_text()] = order.get_text_clause()

        limit_qry: Select[Any] = sqlalchemy.sql.select(*qry_texts)
        limit_qry = limit_qry.select_from(self.select_from)  # type: ignore
        limit_qry = self._apply_filters(limit_qry)
        limit_qry = limit_qry.group_by(*qry_texts)
        for order_by in maxes.values():
            limit_qry = limit_qry.order_by(order_by)
        limit_qry = LimitQuery(limit_count=self.limit_count, binder=self.binder).apply(
            expr=limit_qry
        )
        limit_qry = OffsetQuery(
            query_offset=self.query_offset, binder=self.binder
        ).apply(expr=limit_qry)
        limit_qry = limit_qry.alias("limit_query")  # type: ignore
        on_clause = sqlalchemy.text(
            " AND ".join(
                f"limit_query.{alias}={self.table.name}.{alias}" for alias in pk_aliases
            )
        )
        return limit_qry, on_clause  # type: ignore

    def _apply_expression_modifiers(
        self, expr: sqlalchemy.sql.Select
    ) -> sqlalchemy.sql.Select:
        """
        Receives the select query (might be join) and applies:
        * Filter clauses
        * Exclude filter clauses
        * Limit clauses
        * Offset clauses
        * Order by clauses

        Returns complete ready to run query.

        :param expr: select expression before clauses
        :type expr: sqlalchemy.sql.selectable.Select
        :return: expression with all present clauses applied
        :rtype: sqlalchemy.sql.selectable.Select
        """
        expr = self._apply_filters(expr)
        if not self._pagination_query_required():
            expr = LimitQuery(limit_count=self.limit_count, binder=self.binder).apply(
                expr=expr
            )
            expr = OffsetQuery(
                query_offset=self.query_offset, binder=self.binder
            ).apply(expr=expr)
        expr = OrderQuery(sorted_orders=self.sorted_orders).apply(expr)
        return expr

    def _reset_query_parameters(self) -> None:
        """
        Although it should be created each time before the call we reset the key params
        anyway.
        """
        self.select_from = []
        self.columns = []
        self.used_aliases = []

apply_order_bys_for_primary_model()

Applies order_by queries on main model when it's used as a subquery. That way the subquery with limit and offset only on main model has proper sorting applied and correct models are fetched.

Source code in ormar/queryset/queries/query.py
Python
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def apply_order_bys_for_primary_model(self) -> None:  # noqa: CCR001
    """
    Applies order_by queries on main model when it's used as a subquery.
    That way the subquery with limit and offset only on main model has proper
    sorting applied and correct models are fetched.
    """
    current_table_sorted = False
    if self.order_columns:
        for clause in self.order_columns:
            if clause.is_source_model_order:
                current_table_sorted = True
                self.sorted_orders[clause] = clause.get_text_clause()

    if not current_table_sorted:
        self._apply_default_model_sorting()

build_primary_key_select()

Select only the primary key of the rows the queryset matches, with the joins and filters of build_select_expression but no ordering, limit or offset. Updates and deletes filtering on related models restrict their rows to it::

Text Only
1
2
3
SELECT tracks.id FROM tracks
LEFT OUTER JOIN albums AS t1b26c7_albums ON t1b26c7_albums.id = tracks.album
WHERE t1b26c7_albums.name = :ormar_p0

Returns:

Type Description
sqlalchemy.sql.selectable.Select

select of the primary key columns

Source code in ormar/queryset/queries/query.py
Python
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def build_primary_key_select(self) -> sqlalchemy.sql.Select:
    """
    Select only the primary key of the rows the queryset matches, with the
    joins and filters of ``build_select_expression`` but no ordering, limit
    or offset. Updates and deletes filtering on related models restrict
    their rows to it::

        SELECT tracks.id FROM tracks
        LEFT OUTER JOIN albums AS t1b26c7_albums ON t1b26c7_albums.id = tracks.album
        WHERE t1b26c7_albums.name = :ormar_p0

    :return: select of the primary key columns
    :rtype: sqlalchemy.sql.selectable.Select
    """
    self._join_related_models()
    pk_columns = [
        self.table.c[alias]
        for alias in self.model_cls.ormar_config.pk.column_aliases()
    ]
    expr = sqlalchemy.sql.select(*pk_columns)
    expr = expr.select_from(cast("FromClauseRole", self.select_from))
    expr = self._apply_filters(expr)
    self._reset_query_parameters()
    return expr

build_select_expression()

Main entry point from outside (after proper initialization).

Extracts columns list to fetch, construct all required joins for select related, then applies all conditional and sort clauses.

Returns ready to run query with all joins and clauses.

Returns:

Type Description
sqlalchemy.sql.selectable.Select

ready to run query with all joins and clauses.

Source code in ormar/queryset/queries/query.py
Python
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def build_select_expression(self) -> sqlalchemy.sql.Select:
    """
    Main entry point from outside (after proper initialization).

    Extracts columns list to fetch,
    construct all required joins for select related,
    then applies all conditional and sort clauses.

    Returns ready to run query with all joins and clauses.

    :return: ready to run query with all joins and clauses.
    :rtype: sqlalchemy.sql.selectable.Select
    """
    self._join_related_models()

    if self._pagination_query_required():
        limit_qry, on_clause = self._build_pagination_condition()
        self.select_from = sqlalchemy.sql.join(
            cast("FromClauseRole", self.select_from), limit_qry, on_clause
        )

    expr = sqlalchemy.sql.select(*self.columns)
    expr = expr.select_from(cast("FromClauseRole", self.select_from))

    expr = self._apply_expression_modifiers(expr)

    # print("\n", expr.compile(compile_kwargs={"literal_binds": True}))
    self._reset_query_parameters()

    return expr