Skip to content

fix(migrations):Fix the initial schema by recreating it to match the …#41

Merged
Fl1riX merged 1 commit into
mainfrom
fix/alembic-migrations
Jun 3, 2026
Merged

fix(migrations):Fix the initial schema by recreating it to match the …#41
Fl1riX merged 1 commit into
mainfrom
fix/alembic-migrations

Conversation

@Fl1riX

@Fl1riX Fl1riX commented Jun 3, 2026

Copy link
Copy Markdown
Owner

…current database models.

Summary by Sourcery

Добавить начальную миграцию Alembic, которая определяет базовую схему базы данных для пользователей, банов, magic tokens, сервисов и записей на приём.

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

  • Ввести начальную миграцию Alembic, создающую таблицу users с полями аутентификации и профиля, а также соответствующими индексами.
  • Определить таблицы bans, magic_tokens, services и appointments с ограничениями, внешними ключами и правилами уникальности для моделирования основных доменных связей.
Original summary in English

Summary by Sourcery

Add an Alembic initial migration that defines the core database schema for users, bans, magic tokens, services, and appointments.

New Features:

  • Introduce an initial Alembic migration that creates the users table with authentication and profile fields plus relevant indexes.
  • Define bans, magic_tokens, services, and appointments tables with constraints, foreign keys, and uniqueness rules to model core domain relationships.

@sourcery-ai

sourcery-ai Bot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

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

Добавляет новую начальную миграцию Alembic, которая воссоздаёт схему базы данных в соответствии с текущими моделями SQLAlchemy, определяя основные таблицы, ограничения и индексы, а также полный путь отката (downgrade).

Диаграмма отношений сущностей для новой начальной схемы Alembic

erDiagram
  users {
    int id PK
    int telegram_id
    string username
    string phone
    string email
    boolean is_entrepreneur
    string role
  }

  bans {
    int id PK
    int user_id FK
    int banned_by FK
    int revoked_by FK
    datetime banned_at
    datetime expires_at
    datetime revoked_at
  }

  magic_tokens {
    int id PK
    int telegram_id
    string token
    datetime expires_at
    boolean used
    int user_id FK
  }

  services {
    int id PK
    string name
    int price
    string address
    int entrepreneur_id FK
  }

  appointments {
    int id PK
    datetime date
    int service_id FK
    int entrepreneur_id FK
    int user_id FK
  }

  users ||--o{ bans : user_bans
  users ||--o{ bans : bans_issued
  users ||--o{ bans : bans_revoked

  users ||--o{ magic_tokens : has_tokens

  users ||--o{ services : offers

  users ||--o{ appointments : books
  users ||--o{ appointments : serves_as_entrepreneur

  services ||--o{ appointments : has_appointments

  magic_tokens }o--|| users : token_owner_optional
Loading

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

Изменение Подробности Файлы
Добавить начальную миграцию Alembic, которая определяет полную текущую схему и путь отката.
  • Создать таблицу users с основными полями пользователя, временными метками, флагами ролей и уникальными индексами по email, phone, telegram_id и username.
  • Создать таблицу bans с внешними ключами на users, check-ограничениями, обеспечивающими логику времени бана, индексами по связанным с банами ссылкам на пользователей и частичным уникальным индексом, гарантирующим только один активный бан на пользователя.
  • Создать таблицу magic_tokens для токенов аутентификации на базе Telegram с полями истечения срока действия, отслеживания использования, необязательной связью с пользователем и уникальным ограничением на токен.
  • Создать таблицу services, связанную с пользователями-предпринимателями, с полями цены, адреса, длительности и составным ограничением уникальности по name/address/entrepreneur_id, а также индексом по name.
  • Создать таблицу appointments, ссылающуюся на пользователей и услуги, с составным ограничением уникальности для предотвращения дублирующихся записей и соответствующим откатом, который удаляет таблицы и индексы в обратном порядке зависимостей.
alembic/versions/e3be8dba0fa6_initial_schema.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

Introduces a new Alembic initial migration that recreates the database schema to match the current SQLAlchemy models, defining core tables, constraints, and indexes along with a complete downgrade path.

Entity relationship diagram for new initial Alembic schema

erDiagram
  users {
    int id PK
    int telegram_id
    string username
    string phone
    string email
    boolean is_entrepreneur
    string role
  }

  bans {
    int id PK
    int user_id FK
    int banned_by FK
    int revoked_by FK
    datetime banned_at
    datetime expires_at
    datetime revoked_at
  }

  magic_tokens {
    int id PK
    int telegram_id
    string token
    datetime expires_at
    boolean used
    int user_id FK
  }

  services {
    int id PK
    string name
    int price
    string address
    int entrepreneur_id FK
  }

  appointments {
    int id PK
    datetime date
    int service_id FK
    int entrepreneur_id FK
    int user_id FK
  }

  users ||--o{ bans : user_bans
  users ||--o{ bans : bans_issued
  users ||--o{ bans : bans_revoked

  users ||--o{ magic_tokens : has_tokens

  users ||--o{ services : offers

  users ||--o{ appointments : books
  users ||--o{ appointments : serves_as_entrepreneur

  services ||--o{ appointments : has_appointments

  magic_tokens }o--|| users : token_owner_optional
Loading

File-Level Changes

Change Details Files
Add an Alembic initial migration that defines the full current schema and downgrade path.
  • Create users table with core user fields, timestamps, role flags, and unique indexes on email, phone, telegram_id, and username.
  • Create bans table with foreign keys to users, check constraints enforcing ban timing logic, indexes on ban-related user references, and a partial unique index ensuring only one active ban per user.
  • Create magic_tokens table for Telegram-based authentication tokens with expiration, usage tracking, optional user relation, and a unique token constraint.
  • Create services table linked to entrepreneur users with pricing, address, duration, and a composite uniqueness constraint on name/address/entrepreneur_id plus an index on name.
  • Create appointments table referencing users and services with a composite uniqueness constraint to prevent duplicate appointments and a corresponding downgrade that drops tables and indexes in reverse dependency order.
alembic/versions/e3be8dba0fa6_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.

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

  • Подумайте о том, чтобы явно задать поведение ondelete для внешних ключей (например, от bans, appointments, services, magic_tokens к users), чтобы семантика удаления пользователя была понятной и обеспечивалась на уровне БД, а не основывалась на неявном поведении.
  • Уникальный индекс на bans.user_id с postgresql_where=sa.text('revoked_at IS NULL') «зашивает» условие в виде сырых SQL-выражений; если вы ожидаете, что это будет эволюционировать, рассмотрите использование выражений SQLAlchemy (например, атрибутов sa.Column) для лучшей возможности рефакторинга и переносимости между БД.
Подсказка для AI-агентов
Пожалуйста, устраните замечания из этого код-ревью:

## Общие комментарии
- Подумайте о том, чтобы явно задать поведение `ondelete` для внешних ключей (например, от `bans`, `appointments`, `services`, `magic_tokens` к `users`), чтобы семантика удаления пользователя была понятной и обеспечивалась на уровне БД, а не основывалась на неявном поведении.
- Уникальный индекс на `bans.user_id` с `postgresql_where=sa.text('revoked_at IS NULL')` «зашивает» условие в виде сырых SQL-выражений; если вы ожидаете, что это будет эволюционировать, рассмотрите использование выражений SQLAlchemy (например, атрибутов `sa.Column`) для лучшей возможности рефакторинга и переносимости между БД.

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

Hey - I've left some high level feedback:

  • Consider explicitly defining ondelete behavior on the foreign keys (e.g., from bans, appointments, services, magic_tokens to users) so that user deletion semantics are clear and enforced at the DB level rather than relying on implicit behavior.
  • The unique index on bans.user_id with postgresql_where=sa.text('revoked_at IS NULL') hardcodes the condition as raw SQL; if you expect this to evolve, consider using SQLAlchemy expressions (e.g., sa.Column attributes) for better refactorability and DB portability.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider explicitly defining `ondelete` behavior on the foreign keys (e.g., from `bans`, `appointments`, `services`, `magic_tokens` to `users`) so that user deletion semantics are clear and enforced at the DB level rather than relying on implicit behavior.
- The unique index on `bans.user_id` with `postgresql_where=sa.text('revoked_at IS NULL')` hardcodes the condition as raw SQL; if you expect this to evolve, consider using SQLAlchemy expressions (e.g., `sa.Column` attributes) for better refactorability and DB portability.

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.

@coveralls

coveralls commented Jun 3, 2026

Copy link
Copy Markdown

Coverage Report for CI Build 26884293467

Coverage remained the same at 30.313%

Details

  • Coverage remained the same as the base build.
  • Patch coverage: No coverable lines changed in this PR.
  • No coverage regressions found.

Uncovered Changes

No uncovered changes found.

Coverage Regressions

No coverage regressions found.


Coverage Stats

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

💛 - Coveralls

@Fl1riX Fl1riX merged commit 48803fe into main Jun 3, 2026
4 checks passed
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.

2 participants