Fixing
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Артём Осипов
2026-11-07 00:02:31 +03:00
parent 8c3acc11a7
commit e3c78a5224
26 changed files with 1103 additions and 608 deletions
+11 -14
View File
@@ -1,29 +1,28 @@
import asyncio
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
# 1. Импортируем наши настройки и модели
# DATABASE_URL берётся из окружения (см. src/database.py)
from src.database import DATABASE_URL, Base
from src import models # Обязательно! Чтобы Alembic "увидел" наши таблицы
from src import models # noqa: F401 нужно, чтобы Alembic "увидел" таблицы
config = context.config
# Настройка логирования
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# Метаданные для autogenerate
target_metadata = Base.metadata
# Переопределяем URL подключения из нашего .env (игнорируем alembic.ini)
config.set_main_option("sqlalchemy.url", "postgresql+asyncpg://postgres:postgres@localhost:5433/messenger_db")
# % экранируем, иначе configparser воспримет его как интерполяцию
config.set_main_option("sqlalchemy.url", DATABASE_URL.replace("%", "%%"))
def run_migrations_offline() -> None:
"""Запуск миграций в 'offline' режиме (без подключения к БД)."""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
@@ -34,31 +33,29 @@ def run_migrations_offline() -> None:
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection: Connection) -> None:
"""Непосредственно применение миграций к соединению."""
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> None:
"""Асинхронный запуск миграций."""
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
"""Запуск миграций в 'online' режиме."""
asyncio.run(run_async_migrations())
# Точка входа Alembic
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
run_migrations_online()
@@ -0,0 +1,27 @@
"""messages history index
Revision ID: b7e1f3a9c2d4
Revises: d74c0ccadc85
Create Date: 2026-11-06 12:00:00
"""
from typing import Sequence, Union
from alembic import op
revision: str = "b7e1f3a9c2d4"
down_revision: Union[str, Sequence[str], None] = "d74c0ccadc85"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# Запрос истории: WHERE chat_id = ? AND (created_at, id) > (?, ?) ORDER BY created_at, id
op.create_index("ix_messages_chat_created_id", "messages", ["chat_id", "created_at", "id"])
op.drop_index("ix_messages_chat_id", table_name="messages") # префикс нового индекса
op.drop_index("ix_messages_created_at", table_name="messages") # для этого запроса бесполезен
def downgrade() -> None:
op.create_index("ix_messages_created_at", "messages", ["created_at"])
op.create_index("ix_messages_chat_id", "messages", ["chat_id"])
op.drop_index("ix_messages_chat_created_id", table_name="messages")