"""Index notifications.businessunitid (shopfloor list route filters on it).

businessunitid is a soft-ref column the shopfloor feed filters by; it had no
index. Add ix_notifications_businessunitid (matches the model's index=True).

Idempotent; downgrade drops it.

Revision ID: notifications0002buidx
Revises: notifications0001anchor
"""
from alembic import op
import sqlalchemy as sa


revision = 'notifications0002buidx'
down_revision = 'notifications0001anchor'
branch_labels = None
depends_on = None

_INDEX = 'ix_notifications_businessunitid'


def _index_names(insp, table):
    return {i['name'] for i in insp.get_indexes(table)}


def upgrade():
    bind = op.get_bind()
    insp = sa.inspect(bind)
    if 'notifications' not in insp.get_table_names():
        return
    if _INDEX not in _index_names(insp, 'notifications'):
        op.create_index(_INDEX, 'notifications', ['businessunitid'])


def downgrade():
    bind = op.get_bind()
    insp = sa.inspect(bind)
    if 'notifications' not in insp.get_table_names():
        return
    if _INDEX in _index_names(insp, 'notifications'):
        op.drop_index(_INDEX, table_name='notifications')
