"""add messages.delivery_id The real header Message-ID as delivered, kept even when message_id_hdr is synthesized for a cross-account duplicate (SPEC ยง7.1). It identifies a single delivery, so the same email delivered to several of the user's accounts can be collapsed to one row in the thread view. Backfilled from message_id_hdr for non-synthetic ids; synthetic rows are recovered from the raw blob by a script. Revision ID: 0011 Revises: 0010 Create Date: 2026-07-22 """ from __future__ import annotations from collections.abc import Sequence from alembic import op revision: str = "0011" down_revision: str | None = "0010" branch_labels: str | Sequence[str] | None = None depends_on: str | Sequence[str] | None = None def upgrade() -> None: op.execute("ALTER TABLE messages ADD COLUMN delivery_id text") # Non-synthetic ids are the real Message-ID already; use them directly. op.execute( "UPDATE messages SET delivery_id = message_id_hdr " "WHERE message_id_hdr IS NOT NULL AND message_id_hdr NOT LIKE '%@synthetic.local'" ) op.execute("CREATE INDEX ix_messages_delivery ON messages (user_id, delivery_id)") def downgrade() -> None: op.execute("DROP INDEX IF EXISTS ix_messages_delivery") op.execute("ALTER TABLE messages DROP COLUMN IF EXISTS delivery_id")