Newer
Older
gn-synapse / alembic / versions / 20261003_0004_user_channel.py
""" Канал user — личный лог пользователя: recipient_user_id у доставок, ck_channel с 'user'

Revision ID: c8e4f2b77d10
Revises: b7d2f4a19e60
Create Date: 2026-10-03
"""

from alembic import op
import sqlalchemy as sa


revision = "c8e4f2b77d10"
down_revision = "b7d2f4a19e60"
branch_labels = None
depends_on = None

CHANNEL_WITH_USER = "channel IN ('telegram', 'email', 's2s', 'internal_log', 'user')"
CHANNEL_OLD = "channel IN ('telegram', 'email', 's2s', 'internal_log')"

CHECK_TABLES = ("routing_rule_actions", "channel_targets", "deliveries")


def upgrade() -> None:
    # ck_channel есть на трёх таблицах (см. 0001) — обновить каждую, иначе
    # воркер упадёт на первом user-действии.
    for table in CHECK_TABLES:
        op.drop_constraint("ck_channel", table, type_="check")
    for table in CHECK_TABLES:
        op.create_check_constraint("ck_channel", table, CHANNEL_WITH_USER)
    op.add_column("deliveries", sa.Column("recipient_user_id", sa.String(64), nullable=True))
    op.create_index("ix_deliveries_recipient", "deliveries", ["recipient_user_id", "created_at"])


def downgrade() -> None:
    op.drop_index("ix_deliveries_recipient", table_name="deliveries")
    op.drop_column("deliveries", "recipient_user_id")
    for table in CHECK_TABLES:
        op.drop_constraint("ck_channel", table, type_="check")
    for table in CHECK_TABLES:
        op.create_check_constraint("ck_channel", table, CHANNEL_OLD)