Skip to content

fix: Fix the database migration and prevent this error in the code go…#36

Merged
Fl1riX merged 1 commit into
mainfrom
fix/database-migration
Jun 2, 2026
Merged

fix: Fix the database migration and prevent this error in the code go…#36
Fl1riX merged 1 commit into
mainfrom
fix/database-migration

Conversation

@Fl1riX

@Fl1riX Fl1riX commented Jun 2, 2026

Copy link
Copy Markdown
Owner

…ing forward.

Summary by Sourcery

Изменение хранения роли пользователя и приведение миграции базы данных в соответствие с использованием enum

Новые возможности:

  • Добавлен enum UserRole для представления ролей пользователей в доменной модели

Исправления ошибок:

  • Исправлена начальная миграция Alembic, теперь она явно создаёт тип ENUM user_role до создания таблицы users

Улучшения:

  • Изменён столбец User.role на использование простого строкового поля с значением по умолчанию на основе нового enum UserRole вместо типа SQLAlchemy Enum
Original summary in English

Summary by Sourcery

Adjust user role storage and align database migration with enum usage

New Features:

  • Introduce a UserRole enum to represent user roles in the domain model

Bug Fixes:

  • Fix the initial Alembic migration to explicitly create the user_role ENUM type before creating the users table

Enhancements:

  • Change the User.role column to use a simple String field with a default based on the new UserRole enum instead of a SQLAlchemy Enum type

@sourcery-ai

sourcery-ai Bot commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

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

Рефакторинг обработки ролей пользователя за счёт введения типизированного enum в доменной модели, замены базового столбца на обычную строку и одновременного обеспечения создания устаревшего типа PostgreSQL ENUM в начальной миграции Alembic для совместимости с существующими базами данных.

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

Изменение Подробности Файлы
Уточнить представление роли пользователя в доменной модели, используя Python enum и столбец на основе строки вместо SQLAlchemy Enum.
  • Ввести UserRole StrEnum со значениями USER, ADMIN и MODERATOR для типобезопасного использования ролей в Python-коде.
  • Обновить отображаемый столбец User.role, чтобы использовать String(20) со значением по умолчанию, взятым из UserRole.USER.value, и сохранить его не допускающим NULL.
  • Убрать зависимость от встроенного объявления SQLAlchemy Enum для столбца роли, отделив определение enum в БД от ORM-модели.
src/domain/models/user_model.py
Исправить и усилить начальную миграцию Alembic, чтобы явно создать тип PostgreSQL ENUM для ролей пользователя до создания таблицы users.
  • Определить postgresql.ENUM с именем user_role и значениями user, admin и moderator в шаге upgrade.
  • Создать enum user_role в базе данных через user_role.create(op.get_bind(), checkfirst=True) до создания таблицы users.
  • Оставить поведение downgrade без изменений, за исключением незначительного изменения пробелов (no-op).
alembic/versions/98a1f2f343db_initial_schema.py

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

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

  • Запустить новое ревью: Оставьте комментарий @sourcery-ai review в pull request.
  • Продолжить обсуждение: Отвечайте напрямую на комментарии ревью от Sourcery.
  • Создать задачу GitHub из комментария ревью: Попросите Sourcery создать
    задачу из комментария ревью, ответив на него. Вы также можете ответить на
    комментарий ревью с @sourcery-ai 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, чтобы запустить новое ревью!

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

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

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

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

Original review guide in English

Reviewer's Guide

Refactors the user role handling by introducing a typed enum in the domain model, changing the underlying column to a simple string while ensuring the legacy PostgreSQL ENUM type is created in the initial Alembic migration for compatibility with existing databases.

File-Level Changes

Change Details Files
Refine user role representation in the domain model to use a Python enum and a string-backed column instead of a SQLAlchemy Enum.
  • Introduce a UserRole StrEnum with USER, ADMIN, and MODERATOR values for type-safe role usage in Python code.
  • Update the User.role mapped column to use a String(20) with default taken from UserRole.USER.value and keep it non-nullable.
  • Remove reliance on an inline SQLAlchemy Enum declaration for the role column, decoupling DB enum definition from the ORM model.
src/domain/models/user_model.py
Fix and harden the initial Alembic migration to explicitly create the PostgreSQL ENUM type for user roles before creating the users table.
  • Define a postgresql.ENUM named user_role with user, admin, and moderator values in the upgrade step.
  • Create the user_role enum in the database via user_role.create(op.get_bind(), checkfirst=True) prior to creating the users table.
  • Leave downgrade behavior unchanged aside from a no-op whitespace change.
alembic/versions/98a1f2f343db_initial_schema.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

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Привет — я оставил несколько общих замечаний:

  • Новый UserRole StrEnum определён, но столбец SQLAlchemy всё ещё имеет тип Mapped[str] с String(20) — имеет смысл маппить его напрямую как Enum (Mapped[UserRole] / Enum(UserRole, ...)) для более строгой типизации и согласованности между моделью и БД.
  • В миграции вы создаёте тип ENUM user_role, но не удаляете его в downgrade, из‑за чего в базе могут оставаться «осиротевшие» типы enum; стоит также удалить этот ENUM тип в downgrade.
  • В миграции теперь явно создаётся ENUM user_role, в то время как модель использует обычный String(20) для role; будет хорошо выровнять типы столбцов, чтобы схема Alembic и модель ORM описывали один и тот же тип данных.
Подсказка для AI-агентов
Please address the comments from this code review:

## Overall Comments
- The new `UserRole` StrEnum is defined but the SQLAlchemy column is still typed as `Mapped[str]` with `String(20)`—consider mapping it directly as an Enum (`Mapped[UserRole]` / `Enum(UserRole, ...)`) for stronger typing and consistency between model and DB.
- In the migration you create the `user_role` ENUM type but never drop it in `downgrade`, which can leave orphan enum types in the database; consider dropping the ENUM type there as well.
- The migration now explicitly creates a `user_role` ENUM while the model uses a plain `String(20)` for `role`; it would be good to align the column types so that the Alembic schema and ORM model describe the same data type.

Sourcery бесплатен для open source — если вам нравятся наши ревью, пожалуйста, расскажите о нас ✨
Помогите мне быть полезнее! Пожалуйста, нажимайте 👍 или 👎 под каждым комментарием — я использую этот фидбек, чтобы улучшить ваши ревью.
Original comment in English

Hey - I've left some high level feedback:

  • The new UserRole StrEnum is defined but the SQLAlchemy column is still typed as Mapped[str] with String(20)—consider mapping it directly as an Enum (Mapped[UserRole] / Enum(UserRole, ...)) for stronger typing and consistency between model and DB.
  • In the migration you create the user_role ENUM type but never drop it in downgrade, which can leave orphan enum types in the database; consider dropping the ENUM type there as well.
  • The migration now explicitly creates a user_role ENUM while the model uses a plain String(20) for role; it would be good to align the column types so that the Alembic schema and ORM model describe the same data type.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The new `UserRole` StrEnum is defined but the SQLAlchemy column is still typed as `Mapped[str]` with `String(20)`—consider mapping it directly as an Enum (`Mapped[UserRole]` / `Enum(UserRole, ...)`) for stronger typing and consistency between model and DB.
- In the migration you create the `user_role` ENUM type but never drop it in `downgrade`, which can leave orphan enum types in the database; consider dropping the ENUM type there as well.
- The migration now explicitly creates a `user_role` ENUM while the model uses a plain `String(20)` for `role`; it would be good to align the column types so that the Alembic schema and ORM model describe the same data type.

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.

@Fl1riX Fl1riX merged commit 0227811 into main Jun 2, 2026
4 checks passed
@Fl1riX Fl1riX deleted the fix/database-migration branch June 2, 2026 17:52
@github-actions

github-actions Bot commented Jun 2, 2026

Copy link
Copy Markdown

Coverage Report for CI Build 26837916037

Coverage increased (+0.3%) to 30.313%

Details

  • Coverage increased (+0.3%) from the base build.
  • Patch coverage: No coverable lines changed in this PR.
  • 7 coverage regressions across 1 file.

Uncovered Changes

No uncovered changes found.

Coverage Regressions

7 previously-covered lines in 1 file lost coverage.

File Lines Losing Coverage Coverage
domain/models/user_model.py 7 81.58%

Coverage Stats

Coverage Status
Relevant Lines: 1214
Covered Lines: 368
Line Coverage: 30.31%
Coverage Strength: 0.61 hits per line

💛 - Coveralls

1 similar comment
@github-actions

github-actions Bot commented Jun 2, 2026

Copy link
Copy Markdown

Coverage Report for CI Build 26837916037

Coverage increased (+0.3%) to 30.313%

Details

  • Coverage increased (+0.3%) from the base build.
  • Patch coverage: No coverable lines changed in this PR.
  • 7 coverage regressions across 1 file.

Uncovered Changes

No uncovered changes found.

Coverage Regressions

7 previously-covered lines in 1 file lost coverage.

File Lines Losing Coverage Coverage
domain/models/user_model.py 7 81.58%

Coverage Stats

Coverage Status
Relevant Lines: 1214
Covered Lines: 368
Line Coverage: 30.31%
Coverage Strength: 0.61 hits per line

💛 - Coveralls

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