solution
This commit is contained in:
@@ -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())
|
||||
@@ -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"}
|
||||
@@ -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")
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Общая идемпотентность отправки сообщения
|
||||
|
||||
Revision ID: 0002_message_idempotency
|
||||
Revises: 0001_initial_schema
|
||||
Create Date: 2026-10-30
|
||||
|
||||
Таблица описана в src/messenger/schema.py; DDL повторяет имена ограничений и
|
||||
индексов, чтобы alembic check не находил расхождений.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision = "0002_message_idempotency"
|
||||
down_revision = "0001_initial_schema"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"message_idempotency",
|
||||
sa.Column("user_id", postgresql.UUID(as_uuid=True), nullable=False),
|
||||
sa.Column("chat_id", postgresql.UUID(as_uuid=True), nullable=False),
|
||||
sa.Column("idempotency_key", sa.Text(), nullable=False),
|
||||
sa.Column("request_hash", sa.Text(), nullable=False),
|
||||
sa.Column("message_id", postgresql.UUID(as_uuid=True), nullable=False),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
postgresql.TIMESTAMP(timezone=True),
|
||||
server_default=sa.text("now()"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"char_length(idempotency_key) BETWEEN 1 AND 128",
|
||||
name="ck_message_idempotency_key_length",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["chat_id"], ["chats.id"], name="fk_message_idempotency_chat", ondelete="CASCADE"
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["message_id"],
|
||||
["messages.id"],
|
||||
name="fk_message_idempotency_message",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["user_id"], ["users.id"], name="fk_message_idempotency_user", ondelete="CASCADE"
|
||||
),
|
||||
sa.PrimaryKeyConstraint("user_id", "chat_id", "idempotency_key"),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_message_idempotency_created_at", "message_idempotency", ["created_at"]
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("ix_message_idempotency_created_at", table_name="message_idempotency")
|
||||
op.drop_table("message_idempotency")
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Вложения и связь сообщений с вложениями
|
||||
|
||||
Revision ID: 0003_attachments
|
||||
Revises: 0002_message_idempotency
|
||||
Create Date: 2026-11-06
|
||||
|
||||
DDL повторяет src/messenger/schema.py, включая имена ограничений и индексов,
|
||||
поэтому `alembic check` не находит расхождений. Отдельно ослабляется CHECK
|
||||
текста сообщения: пустая строка теперь допустима только вместе с вложением,
|
||||
а это правило проверяет API (CHECK не может ссылаться на другую таблицу).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision = "0003_attachments"
|
||||
down_revision = "0002_message_idempotency"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"attachments",
|
||||
sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
|
||||
sa.Column("chat_id", postgresql.UUID(as_uuid=True), nullable=False),
|
||||
sa.Column("owner_id", postgresql.UUID(as_uuid=True), nullable=False),
|
||||
sa.Column("object_key", sa.Text(), nullable=False),
|
||||
sa.Column("filename", sa.Text(), nullable=False),
|
||||
sa.Column("content_type", sa.Text(), nullable=False),
|
||||
sa.Column("size_bytes", sa.BigInteger(), nullable=False),
|
||||
sa.Column("sha256", sa.Text(), nullable=False),
|
||||
sa.Column("status", sa.Text(), server_default=sa.text("'pending'"), nullable=False),
|
||||
sa.Column("error_code", sa.Text(), nullable=True),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
postgresql.TIMESTAMP(timezone=True),
|
||||
server_default=sa.text("now()"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
"updated_at",
|
||||
postgresql.TIMESTAMP(timezone=True),
|
||||
server_default=sa.text("now()"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"char_length(filename) BETWEEN 1 AND 255", name="ck_attachments_filename_length"
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"content_type IN ('image/png','image/jpeg')", name="ck_attachments_content_type"
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"size_bytes > 0 AND size_bytes <= 10485760", name="ck_attachments_size_bytes"
|
||||
),
|
||||
sa.CheckConstraint("sha256 ~ '^[a-f0-9]{64}$'", name="ck_attachments_sha256"),
|
||||
sa.CheckConstraint(
|
||||
"status IN ('pending','ready','failed')", name="ck_attachments_status"
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"error_code IS NULL OR char_length(error_code) BETWEEN 1 AND 64",
|
||||
name="ck_attachments_error_code",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["chat_id"], ["chats.id"], name="fk_attachments_chat", ondelete="CASCADE"
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["owner_id"], ["users.id"], name="fk_attachments_owner", ondelete="RESTRICT"
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("object_key", name="uq_attachments_object_key"),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_attachments_chat_id_created_at_id",
|
||||
"attachments",
|
||||
["chat_id", "created_at", "id"],
|
||||
)
|
||||
op.create_index("ix_attachments_status_updated_at", "attachments", ["status", "updated_at"])
|
||||
|
||||
op.create_table(
|
||||
"message_attachments",
|
||||
sa.Column("message_id", postgresql.UUID(as_uuid=True), nullable=False),
|
||||
sa.Column("attachment_id", postgresql.UUID(as_uuid=True), nullable=False),
|
||||
sa.Column("position", sa.SmallInteger(), nullable=False),
|
||||
sa.CheckConstraint(
|
||||
"position >= 0 AND position < 10", name="ck_message_attachments_position"
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["attachment_id"],
|
||||
["attachments.id"],
|
||||
name="fk_message_attachments_attachment",
|
||||
ondelete="RESTRICT",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["message_id"],
|
||||
["messages.id"],
|
||||
name="fk_message_attachments_message",
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("message_id", "attachment_id"),
|
||||
sa.UniqueConstraint(
|
||||
"message_id", "position", name="uq_message_attachments_position"
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_message_attachments_attachment_id",
|
||||
"message_attachments",
|
||||
["attachment_id"],
|
||||
)
|
||||
|
||||
op.drop_constraint("ck_messages_text_length", "messages", type_="check")
|
||||
op.create_check_constraint(
|
||||
"ck_messages_text_length", "messages", "char_length(text) <= 4000"
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_constraint("ck_messages_text_length", "messages", type_="check")
|
||||
op.create_check_constraint(
|
||||
"ck_messages_text_length", "messages", "text <> '' AND char_length(text) <= 4000"
|
||||
)
|
||||
op.drop_index("ix_message_attachments_attachment_id", table_name="message_attachments")
|
||||
op.drop_table("message_attachments")
|
||||
op.drop_index("ix_attachments_status_updated_at", table_name="attachments")
|
||||
op.drop_index("ix_attachments_chat_id_created_at_id", table_name="attachments")
|
||||
op.drop_table("attachments")
|
||||
Reference in New Issue
Block a user