lab 2 solution
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-10-23 17:24:27 +03:00
parent 65003b6119
commit 5c193f24f7
70 changed files with 7881 additions and 17 deletions
+58
View File
@@ -0,0 +1,58 @@
"""Окружение Alembic: URL базы берётся из тех же переменных, что и у приложения."""
from __future__ import annotations
import asyncio
from logging.config import fileConfig
from alembic import context
from sqlalchemy import pool
from sqlalchemy.ext.asyncio import async_engine_from_config
from messenger.config import database_url_from_env
from messenger.schema import METADATA
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# Сравнение идёт ровно с теми объектами, по которым работает приложение:
# расхождение между схемой и миграциями ловится на `alembic check`.
target_metadata = METADATA
def run_migrations_offline() -> None:
"""Режим без подключения: печатает SQL миграции, удобен для ревью."""
context.configure(
url=database_url_from_env(),
target_metadata=target_metadata,
literal_binds=True,
compare_type=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def _run_migrations(connection) -> None:
context.configure(connection=connection, target_metadata=target_metadata, compare_type=True)
with context.begin_transaction():
context.run_migrations()
async def run_migrations_online() -> None:
"""Драйвер асинхронный (asyncpg), поэтому миграции идут через run_sync."""
section = config.get_section(config.config_ini_section, {})
section["sqlalchemy.url"] = database_url_from_env()
engine = async_engine_from_config(section, prefix="sqlalchemy.", poolclass=pool.NullPool)
try:
async with engine.connect() as connection:
await connection.run_sync(_run_migrations)
finally:
await engine.dispose()
if context.is_offline_mode():
run_migrations_offline()
else:
asyncio.run(run_migrations_online())
+24
View File
@@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
+103
View File
@@ -0,0 +1,103 @@
"""Начальная схема: пользователи, чаты, участники и сообщения
Revision ID: 0001_initial_schema
Revises:
Create Date: 2026-10-11
DDL написан вручную и повторяет src/messenger/schema.py: имена ограничений
и индексов совпадают, поэтому `alembic check` не находит расхождений между
схемой в базе и описанием, по которому работают запросы.
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = "0001_initial_schema"
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"users",
sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("username", sa.Text(), nullable=False),
sa.Column("display_name", sa.Text(), nullable=False),
sa.Column("password_hash", sa.Text(), nullable=False),
sa.Column(
"created_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.CheckConstraint(
"char_length(display_name) BETWEEN 1 AND 100", name="ck_users_display_name_length"
),
sa.CheckConstraint(r"username ~ '^[a-z0-9_]{3,32}$'", name="ck_users_username_format"),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("username", name="uq_users_username"),
)
op.create_table(
"chats",
sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("title", sa.Text(), nullable=False),
sa.Column(
"created_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.CheckConstraint("char_length(title) BETWEEN 1 AND 100", name="ck_chats_title_length"),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"chat_members",
sa.Column("chat_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("user_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.ForeignKeyConstraint(
["chat_id"], ["chats.id"], name="fk_chat_members_chat", ondelete="CASCADE"
),
sa.ForeignKeyConstraint(
["user_id"], ["users.id"], name="fk_chat_members_user", ondelete="RESTRICT"
),
sa.PrimaryKeyConstraint("chat_id", "user_id"),
)
op.create_index("ix_chat_members_user_id_chat_id", "chat_members", ["user_id", "chat_id"])
op.create_table(
"messages",
sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("chat_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("sender_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("text", sa.Text(), nullable=False),
sa.Column(
"created_at",
postgresql.TIMESTAMP(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.CheckConstraint(
"text <> '' AND char_length(text) <= 4000", name="ck_messages_text_length"
),
sa.ForeignKeyConstraint(["chat_id"], ["chats.id"], name="fk_messages_chat", ondelete="CASCADE"),
sa.ForeignKeyConstraint(
["sender_id"], ["users.id"], name="fk_messages_sender", ondelete="RESTRICT"
),
sa.PrimaryKeyConstraint("id"),
)
# Порядок истории (created_at, id) и keyset-предикат обслуживает один индекс.
op.create_index("ix_messages_chat_id_created_at_id", "messages", ["chat_id", "created_at", "id"])
def downgrade() -> None:
op.drop_index("ix_messages_chat_id_created_at_id", table_name="messages")
op.drop_table("messages")
op.drop_index("ix_chat_members_user_id_chat_id", table_name="chat_members")
op.drop_table("chat_members")
op.drop_table("chats")
op.drop_table("users")