"""add referrer_domain and referrer_query to page_session

Revision ID: f3086e09b052
Revises: b3f7a2c8d1e5
Create Date: 2026-02-26 16:53:40.340946

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'f3086e09b052'
down_revision = 'b3f7a2c8d1e5'
branch_labels = None
depends_on = None


def _column_exists(table, column):
    conn = op.get_bind()
    result = conn.execute(sa.text(f"PRAGMA table_info({table})"))
    return any(row[1] == column for row in result.fetchall())


def upgrade():
    if not _column_exists("mps_page_session", "referrer_domain"):
        op.add_column(
            "mps_page_session",
            sa.Column("referrer_domain", sa.Unicode(128), nullable=True),
        )
    if not _column_exists("mps_page_session", "referrer_query"):
        op.add_column(
            "mps_page_session",
            sa.Column("referrer_query", sa.Unicode(256), nullable=True),
        )


def downgrade():
    op.drop_column("mps_page_session", "referrer_query")
    op.drop_column("mps_page_session", "referrer_domain")
