"""missing_index

Revision ID: d72102c4391f
Revises: 2caed45e3853
Create Date: 2019-07-12 09:58:47.475000

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'd72102c4391f'
down_revision = '2caed45e3853'
branch_labels = None
depends_on = None

first_agent_version = '19.7.18'

# This is to correct a released version of 2505d6f40bee which did not contain the index idx_held_target_combo_item_key.
# 2505d6f40bee was updated in this commit to create the index and remove it as well.
# This migration serves to create it for those that already upgraded.


def upgrade():
    connection = op.get_bind()
    inspector = sa.inspect(connection)
    has_idx_held_target_combo_item_key = len([ind for ind in inspector.get_indexes('held_ticket_item_modifier_closures') if ind['name'] == 'idx_held_target_combo_item_key']) > 0

    try:
        with op.batch_alter_table('held_ticket_item_modifier_closures', schema=None) as batch_op:
            if not has_idx_held_target_combo_item_key:
                batch_op.create_index('idx_held_target_combo_item_key', ['target_combo_item_key'], unique=False)
    finally:
        op.execute("pragma foreign_keys = 1")


def downgrade():
    # no downgrade here. handled in 2505d6f40bee
    pass
