Files
beavergram/backend/migrations/versions/e2c9a41f7b68_bot_accounts.py

62 lines
1.7 KiB
Python

"""bot accounts
Revision ID: e2c9a41f7b68
Revises: c8f3b6a2d571
Create Date: 2026-09-18 16:00:00.000000
"""
from collections.abc import Sequence
from alembic import op
revision: str = "e2c9a41f7b68"
down_revision: str | None = "c8f3b6a2d571"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
_ACCOUNTS = """
INSERT INTO accounts
(tg_user_id, label, phone, session_name, is_active, is_bot, raw)
SELECT b.bot_id,
coalesce(b.title, '@' || b.username, b.bot_id::text),
NULL,
b.bot_id::text,
b.enabled,
true,
jsonb_build_object('id', b.bot_id, 'username', b.username,
'first_name', b.title)
FROM watched_bots b
ON CONFLICT (tg_user_id) DO NOTHING
"""
_LINK = """
UPDATE watched_bots b SET account_id = a.account_id
FROM accounts a WHERE a.tg_user_id = b.bot_id
"""
_MERGE_MESSAGES = """
INSERT INTO messages
(account_id, chat_id, message_id, date, sender_id, text, raw, has_media)
SELECT b.account_id, u.chat_id, u.item_id, u.ts, u.sender_id, u.text, u.raw,
u.media_kind IS NOT NULL
FROM bot_updates u
JOIN watched_bots b ON b.bot_id = u.bot_id
WHERE u.kind = 'message' AND b.account_id IS NOT NULL
ON CONFLICT (account_id, chat_id, message_id, date) DO NOTHING
"""
def upgrade() -> None:
op.execute("ALTER TABLE accounts ADD COLUMN is_bot boolean NOT NULL DEFAULT false")
op.execute("ALTER TABLE watched_bots ADD COLUMN account_id integer")
op.execute(_ACCOUNTS)
op.execute(_LINK)
op.execute(_MERGE_MESSAGES)
op.execute("DROP TABLE IF EXISTS bot_updates")
def downgrade() -> None:
op.execute("ALTER TABLE watched_bots DROP COLUMN IF EXISTS account_id")
op.execute("ALTER TABLE accounts DROP COLUMN IF EXISTS is_bot")