"""Add sent item ids to held tickets cache

Revision ID: e88d67c3ccf9
Revises:
Create Date: 2017-01-01 20:21:48.733000

"""

import json

from alembic import op
from sqlalchemy import Column, PickleType

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

first_agent_version = '17.1.17'


def upgrade():
    """
    Use batch-operations to support sqlite

    > with op.batch_alter_table('table_name') as batch_op:
    >     pass
    """
    connection = op.get_bind()
    try:
        connection.execute('PRAGMA foreign_keys = "0";')

        with op.batch_alter_table('held_tickets') as batch_op:
            batch_op.add_column(Column('held_item_ids', PickleType(pickler=json), nullable=False, server_default='[]'))
            batch_op.add_column(Column('held_discount_ids', PickleType(pickler=json), nullable=False, server_default='[]'))

    finally:
        connection.execute('PRAGMA foreign_keys = "1";')


def downgrade():
    """
    Use batch-operations to support sqlite

    > with op.batch_alter_table('table_name') as batch_op:
    >     pass
    """
    connection = op.get_bind()
    try:
        connection.execute('PRAGMA foreign_keys = "0";')

        with op.batch_alter_table('held_tickets') as batch_op:
            batch_op.drop_column('held_item_ids')
            batch_op.drop_column('held_discount_ids')

    finally:
        connection.execute('PRAGMA foreign_keys = "1";')