Skip to content

fix(auth): Fix data type error when creating a user in the database#5

Merged
Fl1riX merged 1 commit into
mainfrom
fix/registration
Mar 11, 2026
Merged

fix(auth): Fix data type error when creating a user in the database#5
Fl1riX merged 1 commit into
mainfrom
fix/registration

Conversation

@Fl1riX
Copy link
Copy Markdown
Owner

@Fl1riX Fl1riX commented Mar 11, 2026

Summary by Sourcery

Bug Fixes:

  • Предотвращение ошибок несоответствия типов при поиске во время регистрации пользователя за счёт приведения telegram_id к строке перед выполнением запроса к базе данных.
Original summary in English

Summary by Sourcery

Bug Fixes:

  • Prevent type mismatch errors during user registration lookups by casting telegram_id to a string before querying the database.

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Mar 11, 2026

Руководство для ревьюера (свернуто для маленьких PR)

Руководство для ревьюера

Изменяет логику поиска пользователя в сервисе аутентификации так, чтобы telegram_id всегда рассматривался как строка при запросах к базе данных, предотвращая несоответствия типов данных при создании пользователя.

Диаграмма последовательности для поиска пользователя в auth_service find_user_registration

sequenceDiagram
    actor Client
    participant AuthService
    participant DB
    participant User

    Client->>AuthService: find_user_registration(user, db)
    AuthService->>AuthService: build conditions with email and phone
    alt telegram_id is not None
        AuthService->>AuthService: telegram_id_str = str(user.telegram_id)
        AuthService->>AuthService: add condition User.telegram_id == telegram_id_str
    end
    AuthService->>DB: execute(select(User).where(or(conditions)))
    DB-->>AuthService: result
    AuthService-->>Client: user or None
Loading

Диаграмма классов обработки telegram_id в auth_service и модели User

classDiagram
    class AuthService {
        +find_user_registration(user, db)
    }

    class User {
        +email
        +phone
        +telegram_id string
    }

    AuthService ..> User : queries
Loading

Изменения на уровне файлов

Изменение Подробности Файлы
Нормализовать telegram_id до строки при формировании условий поиска пользователя в сервисе аутентификации.
  • Обновить построение условия для telegram_id, чтобы приводить входящее значение telegram_id к строке перед сравнением с User.telegram_id
  • Сохранить существующее поведение для условий поиска по email и phone, а также общую структуру запроса
src/domain/services/auth_service.py

Подсказки и команды

Взаимодействие с Sourcery

  • Запустить новое ревью: Оставьте комментарий @sourcery-ai review в pull request.
  • Продолжать обсуждения: Отвечайте напрямую на комментарии ревью от Sourcery.
  • Создать задачу GitHub из комментария ревью: Попросите Sourcery создать
    issue из комментария ревью, ответив на него. Также можно ответить на
    комментарий ревью с @sourcery-ai issue, чтобы создать issue из этого комментария.
  • Сгенерировать заголовок pull request: Напишите @sourcery-ai в любом месте
    заголовка pull request, чтобы в любой момент сгенерировать заголовок. Также можно
    оставить комментарий @sourcery-ai title в pull request, чтобы (пере)сгенерировать
    заголовок в любой момент.
  • Сгенерировать описание pull request: Напишите @sourcery-ai summary в любом
    месте тела pull request, чтобы в любой момент сгенерировать описание PR именно там,
    где вы хотите. Также можно оставить комментарий @sourcery-ai summary в pull request,
    чтобы (пере)сгенерировать описание в любой момент.
  • Сгенерировать руководство для ревьюера: Оставьте комментарий
    @sourcery-ai guide в pull request, чтобы (пере)сгенерировать руководство
    для ревьюера в любой момент.
  • Разрешить все комментарии Sourcery: Оставьте комментарий
    @sourcery-ai resolve в pull request, чтобы отметить все комментарии Sourcery
    как решённые. Полезно, если вы уже учли все комментарии и больше не хотите их видеть.
  • Отклонить все ревью Sourcery: Оставьте комментарий @sourcery-ai dismiss
    в pull request, чтобы отклонить все существующие ревью Sourcery. Особенно полезно,
    если вы хотите начать с нуля с новым ревью — не забудьте оставить комментарий
    @sourcery-ai review, чтобы запустить новое ревью!

Настройка работы Sourcery

Зайдите в свою панель управления, чтобы:

  • Включать или отключать функции ревью, такие как автоматически сгенерированное
    описание pull request, руководство для ревьюера и другие.
  • Изменить язык ревью.
  • Добавлять, удалять или редактировать пользовательские инструкции для ревью.
  • Настраивать другие параметры ревью.

Получение помощи

Original review guide in English
Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Adjusts user lookup logic in the auth service to consistently treat telegram_id as a string when querying the database, preventing data type mismatches during user creation.

Sequence diagram for auth_service find_user_registration user lookup

sequenceDiagram
    actor Client
    participant AuthService
    participant DB
    participant User

    Client->>AuthService: find_user_registration(user, db)
    AuthService->>AuthService: build conditions with email and phone
    alt telegram_id is not None
        AuthService->>AuthService: telegram_id_str = str(user.telegram_id)
        AuthService->>AuthService: add condition User.telegram_id == telegram_id_str
    end
    AuthService->>DB: execute(select(User).where(or(conditions)))
    DB-->>AuthService: result
    AuthService-->>Client: user or None
Loading

Class diagram for auth_service and User model telegram_id handling

classDiagram
    class AuthService {
        +find_user_registration(user, db)
    }

    class User {
        +email
        +phone
        +telegram_id string
    }

    AuthService ..> User : queries
Loading

File-Level Changes

Change Details Files
Normalize telegram_id to string when constructing user lookup conditions in the auth service.
  • Update condition building for telegram_id to cast incoming telegram_id value to string before comparing with User.telegram_id
  • Preserve existing behavior for email and phone lookup conditions and overall query structure
src/domain/services/auth_service.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Привет — я нашёл 1 проблему и оставил несколько общих комментариев:

  • Если telegram_id концептуально является числом, но хранится в БД как строка, стоит рассмотреть нормализацию этого поля на уровне модели/ORM (например, через кастомный тип или преобразование в модели User), а не только в этом конкретном запросе, чтобы избежать подобных несоответствий в других местах.
  • Чтобы поведение оставалось единообразным, имеет смысл применять такую же нормализацию через str() для telegram_id везде, где оно записывается в базу или сравнивается в запросах, чтобы исправление не ограничивалось только этим одним маршрутом выполнения запроса.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- If `telegram_id` is conceptually numeric but stored as a string in the DB, consider normalizing this at the model/ORM level (e.g., via a custom type or conversion in the `User` model) rather than only in this query to avoid similar mismatches elsewhere.
- To keep behavior consistent, you may want to apply the same `str()` normalization for `telegram_id` wherever it is written to or compared in the database, so this fix isn't limited just to this one query path.

## Individual Comments

### Comment 1
<location path="src/domain/services/auth_service.py" line_range="40" />
<code_context>
         conditions.append(User.phone == user.phone)
         if user.telegram_id is not None:
-            conditions.append(User.telegram_id == user.telegram_id)
+            conditions.append(User.telegram_id == str(user.telegram_id))

         result = await db.execute(select(User).where(
</code_context>
<issue_to_address>
**suggestion:** Consider normalizing `telegram_id` types earlier instead of casting at query time.

Casting `user.telegram_id` to `str` in the query can mask mismatches between your API schema and persistence layer. If `telegram_id` should be a string, align the types in the `User` model and `UserRegister` schema and handle normalization at the boundary (e.g., schema validators or a helper) so queries remain pure filters and future changes to `telegram_id` representation are less error‑prone.

Suggested implementation:

```python
        conditions.append(User.email == user.email)
        conditions.append(User.phone == user.phone)

        # normalize telegram_id to string once at the service boundary
        if user.telegram_id is not None and not isinstance(user.telegram_id, str):
            user.telegram_id = str(user.telegram_id)

        if user.telegram_id is not None:
            conditions.append(User.telegram_id == user.telegram_id)

        result = await db.execute(select(User).where(
            or_(*conditions)

```

To fully align with the suggestion about schema/model consistency, you will likely also want to:
1. Ensure the `telegram_id` field in your `UserRegister` (or equivalent) schema is declared as a `str` and, if needed, add a validator to coerce incoming numeric values to strings.
2. Confirm the `telegram_id` column on the `User` model is a string type (e.g., `String`/`VARCHAR`) so the persistence layer matches the API contract.
These changes will move all type normalization to the boundaries (schema/model) and keep service/query code strictly typed and declarative.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Помогите мне стать полезнее! Пожалуйста, нажимайте 👍 или 👎 на каждом комментарии — я буду использовать эту обратную связь, чтобы улучшать ревью.
Original comment in English

Hey - I've found 1 issue, and left some high level feedback:

  • If telegram_id is conceptually numeric but stored as a string in the DB, consider normalizing this at the model/ORM level (e.g., via a custom type or conversion in the User model) rather than only in this query to avoid similar mismatches elsewhere.
  • To keep behavior consistent, you may want to apply the same str() normalization for telegram_id wherever it is written to or compared in the database, so this fix isn't limited just to this one query path.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- If `telegram_id` is conceptually numeric but stored as a string in the DB, consider normalizing this at the model/ORM level (e.g., via a custom type or conversion in the `User` model) rather than only in this query to avoid similar mismatches elsewhere.
- To keep behavior consistent, you may want to apply the same `str()` normalization for `telegram_id` wherever it is written to or compared in the database, so this fix isn't limited just to this one query path.

## Individual Comments

### Comment 1
<location path="src/domain/services/auth_service.py" line_range="40" />
<code_context>
         conditions.append(User.phone == user.phone)
         if user.telegram_id is not None:
-            conditions.append(User.telegram_id == user.telegram_id)
+            conditions.append(User.telegram_id == str(user.telegram_id))

         result = await db.execute(select(User).where(
</code_context>
<issue_to_address>
**suggestion:** Consider normalizing `telegram_id` types earlier instead of casting at query time.

Casting `user.telegram_id` to `str` in the query can mask mismatches between your API schema and persistence layer. If `telegram_id` should be a string, align the types in the `User` model and `UserRegister` schema and handle normalization at the boundary (e.g., schema validators or a helper) so queries remain pure filters and future changes to `telegram_id` representation are less error‑prone.

Suggested implementation:

```python
        conditions.append(User.email == user.email)
        conditions.append(User.phone == user.phone)

        # normalize telegram_id to string once at the service boundary
        if user.telegram_id is not None and not isinstance(user.telegram_id, str):
            user.telegram_id = str(user.telegram_id)

        if user.telegram_id is not None:
            conditions.append(User.telegram_id == user.telegram_id)

        result = await db.execute(select(User).where(
            or_(*conditions)

```

To fully align with the suggestion about schema/model consistency, you will likely also want to:
1. Ensure the `telegram_id` field in your `UserRegister` (or equivalent) schema is declared as a `str` and, if needed, add a validator to coerce incoming numeric values to strings.
2. Confirm the `telegram_id` column on the `User` model is a string type (e.g., `String`/`VARCHAR`) so the persistence layer matches the API contract.
These changes will move all type normalization to the boundaries (schema/model) and keep service/query code strictly typed and declarative.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread src/domain/services/auth_service.py
@Fl1riX Fl1riX merged commit 7d6e432 into main Mar 11, 2026
3 checks passed
@Fl1riX Fl1riX deleted the fix/registration branch March 14, 2026 18:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant