"""Set totals attributes to nullable

Revision ID: 8d1e358cc28b
Revises: 31351fc3f3e4
Create Date: 2017-06-21 16:23:00.040000

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '8d1e358cc28b'
down_revision = '31351fc3f3e4'
branch_labels = None
depends_on = None

first_agent_version = '17.6.27'


def upgrade():
    connection = op.get_bind()
    try:
        connection.execute('PRAGMA foreign_keys = "0";')

        with op.batch_alter_table('held_ticket_totals') as batch_op:
            batch_op.alter_column('discounts', nullable=True)
            batch_op.alter_column('items', nullable=True)

        with op.batch_alter_table('held_ticket_discounts') as batch_op:
            batch_op.alter_column('value', nullable=True)

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



def downgrade():
    connection = op.get_bind()
    try:
        connection.execute('PRAGMA foreign_keys = "0";')

        connection.execute('UPDATE held_ticket_totals SET discounts = 0 WHERE discounts IS NULL')
        connection.execute('UPDATE held_ticket_totals SET items = 0 WHERE items IS NULL')

        with op.batch_alter_table('held_ticket_totals') as batch_op:
            batch_op.alter_column('discounts', nullable=False)
            batch_op.alter_column('items', nullable=False)

        connection.execute('UPDATE held_ticket_discounts SET value = 0 WHERE value IS NULL')

        with op.batch_alter_table('held_ticket_discounts') as batch_op:
            batch_op.alter_column('value', nullable=False)

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