fix(migrations):Fix the initial schema by recreating it to match the …#41
Merged
Conversation
…current database models.
Contributor
Руководство для ревьюераДобавляет новую начальную миграцию Alembic, которая воссоздаёт схему базы данных в соответствии с текущими моделями SQLAlchemy, определяя основные таблицы, ограничения и индексы, а также полный путь отката (downgrade). Диаграмма отношений сущностей для новой начальной схемы AlembicerDiagram
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
Изменения на уровне файлов
Подсказки и командыВзаимодействие с Sourcery
Настройка работыЗайдите в свою панель управления, чтобы:
Получение помощи
Original review guide in EnglishReviewer's GuideIntroduces 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 schemaerDiagram
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
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Contributor
There was a problem hiding this comment.
Привет — я оставил несколько общих комментариев:
- Подумайте о том, чтобы явно задать поведение
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
ondeletebehavior on the foreign keys (e.g., frombans,appointments,services,magic_tokenstousers) 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_idwithpostgresql_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.Columnattributes) 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.Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
Coverage Report for CI Build 26884293467Coverage remained the same at 30.313%Details
Uncovered ChangesNo uncovered changes found. Coverage RegressionsNo coverage regressions found. Coverage Stats
💛 - Coveralls |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
…current database models.
Summary by Sourcery
Добавить начальную миграцию Alembic, которая определяет базовую схему базы данных для пользователей, банов, magic tokens, сервисов и записей на приём.
Новые возможности:
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: