Skip to content

join

SqlJoin

Source code in ormar/queryset/join.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
class SqlJoin:
    def __init__(  # noqa:  CFQ002
        self,
        used_aliases: list,
        select_from: sqlalchemy.sql.Select,
        columns: list[sqlalchemy.Column],
        excludable: "ExcludableItems",
        order_columns: Optional[list["OrderAction"]],
        sorted_orders: dict,
        main_model: type["Model"],
        relation_name: str,
        relation_str: str,
        related_models: Any = None,
        own_alias: str = "",
        already_sorted: Optional[dict] = None,
    ) -> None:
        self.relation_name = relation_name
        self.related_models = related_models or []
        self.select_from = select_from
        self.columns = columns
        self.excludable = excludable

        self.order_columns = order_columns
        self.sorted_orders = sorted_orders
        self.already_sorted = already_sorted or dict()

        self.main_model = main_model
        self.own_alias = own_alias
        self.used_aliases = used_aliases
        self.target_field = self.main_model.ormar_config.model_fields[
            self.relation_name
        ]

        self._next_model: Optional[type["Model"]] = None
        self.next_alias = ""

        self.relation_str = relation_str

    @property
    def next_model(self) -> type["Model"]:
        if not self._next_model:  # pragma: nocover
            raise RelationshipInstanceError(
                "Cannot link to related table if relation.to model is not set."
            )
        return self._next_model

    @next_model.setter
    def next_model(self, value: type["Model"]) -> None:
        self._next_model = value

    @property
    def to_table(self) -> sqlalchemy.Table:
        """
        Shortcut to table name of the next model
        :return: name of the target table
        :rtype: str
        """
        return self.next_model.ormar_config.table

    def _on_clause(self, link: "RelationLink", previous_alias: str) -> TextClause:
        """
        Combines every column pair of the link into the join condition, the
        target table aliased by its relation path::

            t1b26c7_albums.id = tracks.album

        :param link: columns connecting the previous table to the joined one
        :type link: RelationLink
        :param previous_alias: alias of previous table, empty for the main table
        :type previous_alias: str
        :return: clause combining all column pairs
        :rtype: sqlalchemy.text
        """
        dialect = self.main_model.ormar_config.database.dialect
        quoter = dialect.identifier_preparer.quote
        from_table_name = link.source.ormar_config.tablename
        to_table_name = self.to_table.name
        conditions = []
        for pair in link.pairs:
            left_part = (
                f"{quoter(f'{self.next_alias}_{to_table_name}')}"
                f".{quoter(pair.target_column)}"
            )
            if not previous_alias:
                right_part = f"{quoter(from_table_name)}.{quoter(pair.source_column)}"
            else:
                right_part = (
                    f"{quoter(f'{previous_alias}_{from_table_name}')}"
                    f".{pair.source_column}"
                )
            conditions.append(f"{left_part}={right_part}")
        return text(" AND ".join(conditions))

    def build_join(self) -> tuple[list, sqlalchemy.sql.Select, list, dict]:
        """
        Main external access point for building a join.
        Splits the join definition, updates fields and exclude_fields if needed,
        handles switching to through models for m2m relations, returns updated lists of
        used_aliases and sort_orders.

        :return: list of used aliases, select from, list of aliased columns, sort orders
        :rtype: tuple[list[str], Join, list[TextClause], dict]
        :raises RelationshipInstanceError: if a through model is selected directly
        """
        if self.target_field.is_through:
            raise RelationshipInstanceError(
                f"Relation '{self.relation_str}' points to a through model, "
                "select the many to many relation instead - "
                "the through model is loaded with it."
            )
        if self.target_field.is_multi:
            self._process_m2m_through_table()

        self.next_model = self.target_field.to
        self._forward_join(relation_path=self.relation_str)

        self._process_following_joins()

        return (self.used_aliases, self.select_from, self.columns, self.sorted_orders)

    def _forward_join(self, relation_path: str) -> None:
        """
        Process actual join, the joined table is aliased by its relation path.

        :param relation_path: path of the joined table from the query root model
        :type relation_path: str
        :raises QueryDefinitionError: if two joined tables would share an alias
        """
        self.next_alias = alias_for(relation_path)
        if self.next_alias in self.used_aliases:
            raise QueryDefinitionError(
                f"Alias '{self.next_alias}' of relation '{relation_path}' collides "
                "with an already joined relation."
            )
        self._process_join()

    def _process_following_joins(self) -> None:
        """
        Iterates through nested models to create subsequent joins.
        """
        for related_name in self.related_models:
            remainder = None
            if (
                isinstance(self.related_models, dict)
                and self.related_models[related_name]
            ):
                remainder = self.related_models[related_name]
            self._process_deeper_join(related_name=related_name, remainder=remainder)

    def _process_deeper_join(self, related_name: str, remainder: Any) -> None:
        """
        Creates nested recurrent instance of SqlJoin for each nested join table,
        updating needed return params here as a side effect.

        Updated are:

        * self.used_aliases,
        * self.select_from,
        * self.columns,
        * self.sorted_orders,

        :param related_name: name of the relation to follow
        :type related_name: str
        :param remainder: deeper tables if there are more nested joins
        :type remainder: Any
        """
        sql_join = SqlJoin(
            used_aliases=self.used_aliases,
            select_from=self.select_from,
            columns=self.columns,
            excludable=self.excludable,
            order_columns=self.order_columns,
            sorted_orders=self.sorted_orders,
            main_model=self.next_model,
            relation_name=related_name,
            related_models=remainder,
            relation_str="__".join([self.relation_str, related_name]),
            own_alias=self.next_alias,
            already_sorted=self.already_sorted,
        )
        (
            self.used_aliases,
            self.select_from,
            self.columns,
            self.sorted_orders,
        ) = sql_join.build_join()

    def _process_m2m_through_table(self) -> None:
        """
        Process Through table of the ManyToMany relation so that source table is
        linked to the through table (one additional join)

        Replaces needed parameters like:

        * self.next_model,
        * self.next_alias,
        * self.relation_name,
        * self.own_alias,
        * self.target_field

        To point to through model
        """
        new_part = self.target_field.through_target_field_name()  # type: ignore

        self.next_model = self.target_field.through
        self._forward_join(
            relation_path=f"{self.relation_str}__{self.target_field.through.get_name()}"
        )

        self.relation_name = new_part
        self.own_alias = self.next_alias
        self.target_field = self.next_model.ormar_config.model_fields[
            self.relation_name
        ]

    def _process_join(self) -> None:  # noqa: CFQ002
        """
        Resolves to and from column names and table names.

        Produces on_clause.

        Performs actual join updating select_from parameter.

        Adds aliases of required column to list of columns to include in query.

        Updates the used aliases list directly.

        Process order_by causes for non m2m relations.

        """
        relation_field = cast("ForeignKeyField", self.target_field)
        on_clause = self._on_clause(
            link=relation_field.link, previous_alias=self.own_alias
        )
        target_table = prefixed_table(alias=self.next_alias, table=self.to_table)
        self.select_from = sqlalchemy.sql.outerjoin(
            self.select_from,  # type: ignore
            target_table,
            on_clause,
        )

        self._get_order_bys()

        self_related_fields = self.next_model.own_table_columns(
            model=self.next_model,
            excludable=self.excludable,
            alias=self.next_alias,
            use_alias=True,
        )
        self.columns.extend(
            prefixed_columns(
                self.next_alias,
                target_table,  # type: ignore
                self_related_fields,
            )
        )
        self.used_aliases.append(self.next_alias)

    def _set_default_primary_key_order_by(self) -> None:
        for order_by in self.next_model.ormar_config.orders_by:
            for clause in order_actions_for(
                order_str=order_by, model_cls=self.next_model, alias=self.next_alias
            ):
                self.sorted_orders[clause] = clause.get_text_clause()

    def _verify_allowed_order_field(self, order_by: str) -> None:
        """
        Verifies if proper field string is used.
        :param order_by: string with order by definition
        :type order_by: str
        """
        parts = order_by.split("__")
        if len(parts) > 2 or parts[0] != self.target_field.through.get_name():
            raise ModelDefinitionError(
                "You can order the relation only by related or link table columns!"
            )

    def _get_alias_and_model(self, order_by: str) -> tuple[str, type["Model"]]:
        """
        Returns proper model and alias to be applied in the clause.

        :param order_by: string with order by definition
        :type order_by: str
        :return: alias and model to be used in clause
        :rtype: tuple[str, type["Model"]]
        """
        if self.target_field.is_multi and "__" in order_by:
            self._verify_allowed_order_field(order_by=order_by)
            return self.next_alias, self.target_field.owner
        return alias_for(self.relation_str), self.target_field.to

    def _get_order_bys(self) -> None:  # noqa: CCR001
        """
        Triggers construction of order bys if they are given.
        Otherwise by default each table is sorted by a primary key column asc.
        """
        alias = self.next_alias
        current_table_sorted = False
        if f"{alias}_{self.next_model.get_name()}" in self.already_sorted:
            current_table_sorted = True
        if self.order_columns:
            for condition in self.order_columns:
                if condition.check_if_filter_apply(
                    target_model=self.next_model, alias=alias
                ):
                    current_table_sorted = True
                    self.sorted_orders[condition] = condition.get_text_clause()
                    self.already_sorted[
                        f"{self.next_alias}_{self.next_model.get_name()}"
                    ] = condition
        if self.target_field.orders_by and not current_table_sorted:
            current_table_sorted = True
            for order_by in self.target_field.orders_by:
                alias, model = self._get_alias_and_model(order_by=order_by)
                for clause in order_actions_for(
                    order_str=order_by, model_cls=model, alias=alias
                ):
                    self.sorted_orders[clause] = clause.get_text_clause()
                    self.already_sorted[f"{alias}_{model.get_name()}"] = clause

        if not current_table_sorted and not self.target_field.is_multi:
            self._set_default_primary_key_order_by()

to_table property

Shortcut to table name of the next model

Returns:

Type Description
str

name of the target table

build_join()

Main external access point for building a join. Splits the join definition, updates fields and exclude_fields if needed, handles switching to through models for m2m relations, returns updated lists of used_aliases and sort_orders.

Returns:

Type Description
tuple[list[str], Join, list[TextClause], dict]

list of used aliases, select from, list of aliased columns, sort orders

Raises:

Type Description
RelationshipInstanceError

if a through model is selected directly

Source code in ormar/queryset/join.py
Python
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
def build_join(self) -> tuple[list, sqlalchemy.sql.Select, list, dict]:
    """
    Main external access point for building a join.
    Splits the join definition, updates fields and exclude_fields if needed,
    handles switching to through models for m2m relations, returns updated lists of
    used_aliases and sort_orders.

    :return: list of used aliases, select from, list of aliased columns, sort orders
    :rtype: tuple[list[str], Join, list[TextClause], dict]
    :raises RelationshipInstanceError: if a through model is selected directly
    """
    if self.target_field.is_through:
        raise RelationshipInstanceError(
            f"Relation '{self.relation_str}' points to a through model, "
            "select the many to many relation instead - "
            "the through model is loaded with it."
        )
    if self.target_field.is_multi:
        self._process_m2m_through_table()

    self.next_model = self.target_field.to
    self._forward_join(relation_path=self.relation_str)

    self._process_following_joins()

    return (self.used_aliases, self.select_from, self.columns, self.sorted_orders)