|
| 1 | +# SPDX-FileCopyrightText: 2024-2025 MTS PJSC |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from collections.abc import Collection |
| 6 | + |
| 7 | +from sqlalchemy import ColumnElement, CompoundSelect, Select, SQLColumnExpression, any_, asc, desc, func, select |
| 8 | +from sqlalchemy.orm import selectinload |
| 9 | + |
| 10 | +from data_rentgen.db.models.tag import Tag |
| 11 | +from data_rentgen.db.models.tag_value import TagValue |
| 12 | +from data_rentgen.db.repositories.base import Repository |
| 13 | +from data_rentgen.db.utils.search import make_tsquery, ts_match, ts_rank |
| 14 | +from data_rentgen.dto.pagination import PaginationDTO |
| 15 | + |
| 16 | + |
| 17 | +class TagRepository(Repository[Tag]): |
| 18 | + async def paginate( |
| 19 | + self, |
| 20 | + page: int, |
| 21 | + page_size: int, |
| 22 | + tag_ids: Collection[int], |
| 23 | + search_query: str | None, |
| 24 | + ) -> PaginationDTO[Tag]: |
| 25 | + where = [] |
| 26 | + if tag_ids: |
| 27 | + where.append(Tag.id == any_(list(tag_ids))) # type: ignore[arg-type] |
| 28 | + |
| 29 | + query: Select | CompoundSelect |
| 30 | + order_by: list[ColumnElement | SQLColumnExpression] |
| 31 | + if search_query: |
| 32 | + tsquery = make_tsquery(search_query) |
| 33 | + |
| 34 | + tag_stmt = select(Tag.id, Tag.name, ts_rank(Tag.search_vector, tsquery).label("search_rank")).where( |
| 35 | + ts_match(Tag.search_vector, tsquery), |
| 36 | + *where, |
| 37 | + ) |
| 38 | + value_stmt = ( |
| 39 | + select(Tag.id, Tag.name, ts_rank(TagValue.search_vector, tsquery).label("search_rank")) |
| 40 | + .join(TagValue, TagValue.tag_id == Tag.id) |
| 41 | + .where(ts_match(TagValue.search_vector, tsquery), *where) |
| 42 | + ) |
| 43 | + union_cte = tag_stmt.union_all(value_stmt).cte("tag_union") |
| 44 | + query = select( |
| 45 | + union_cte.c.id, |
| 46 | + union_cte.c.name, |
| 47 | + func.max(union_cte.c.search_rank).label("search_rank"), |
| 48 | + ).group_by(union_cte.c.id, union_cte.c.name) |
| 49 | + |
| 50 | + order_by = [desc("search_rank"), asc("name")] |
| 51 | + else: |
| 52 | + query = select(Tag).where(*where) |
| 53 | + order_by = [Tag.name] |
| 54 | + |
| 55 | + options = [ |
| 56 | + selectinload(Tag.tag_values), |
| 57 | + ] |
| 58 | + |
| 59 | + return await self._paginate_by_query( |
| 60 | + query=query, |
| 61 | + order_by=order_by, |
| 62 | + options=options, |
| 63 | + page=page, |
| 64 | + page_size=page_size, |
| 65 | + ) |
0 commit comments