Files
mtusi2026lab2/alembic/versions/002_history_constraints.py
T
Zyulina_Ekaterina 3af3a132ca
Skeleton contracts / contracts (pull_request) Canceled after 0s
Лабораторная 2:Оценка 4
2026-10-19 23:09:12 +03:00

36 lines
1.5 KiB
Python

"""Add membership uniqueness and the keyset history index.
Revision ID: 002
Revises: 001
Create Date: 2026-10-14
"""
from alembic import op
import sqlalchemy as sa
revision = '002'
down_revision = '001'
branch_labels = None
depends_on = None
def upgrade():
# Older schemas allowed nullable timestamps. Backfill before tightening the
# constraint so the migration also works on an existing populated database.
for table in ('users', 'sessions', 'chats', 'messages'):
op.execute(sa.text(f'UPDATE {table} SET created_at = CURRENT_TIMESTAMP WHERE created_at IS NULL'))
op.alter_column(table, 'created_at', existing_type=sa.DateTime(timezone=True), nullable=False)
op.create_unique_constraint('uq_chat_member', 'chat_members', ['chat_id', 'user_id'])
op.create_index('ix_chat_members_user_chat', 'chat_members', ['user_id', 'chat_id'])
op.drop_index('ix_messages_chat_created', table_name='messages')
op.create_index('ix_messages_chat_created_id', 'messages', ['chat_id', 'created_at', 'id'])
def downgrade():
op.drop_index('ix_messages_chat_created_id', table_name='messages')
op.create_index('ix_messages_chat_created', 'messages', ['chat_id', 'created_at'])
op.drop_index('ix_chat_members_user_chat', table_name='chat_members')
op.drop_constraint('uq_chat_member', 'chat_members', type_='unique')
for table in ('users', 'sessions', 'chats', 'messages'):
op.alter_column(table, 'created_at', existing_type=sa.DateTime(timezone=True), nullable=True)