"""make_pay_rate_wage_nullable

Revision ID: 62f8d9027964
Revises: 79711a8b68e7
Create Date: 2018-07-10 16:46:04.025000

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '62f8d9027964'
down_revision = '79711a8b68e7'
branch_labels = None
depends_on = None

first_agent_version = '18.7.10'


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('pay_rates') as batch_op:
            batch_op.alter_column('rate', nullable=True)

        with op.batch_alter_table('pay_rate_levels') as batch_op:
            batch_op.alter_column('rate', nullable=True)

    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";')
        connection.execute('UPDATE pay_rates SET rate = 0 WHERE rate IS NULL')

        with op.batch_alter_table('pay_rates') as batch_op:
            batch_op.alter_column('rate', nullable=False)

        connection.execute('UPDATE pay_rate_levels SET rate = 0 WHERE rate IS NULL')

        with op.batch_alter_table('pay_rate_levels') as batch_op:
            batch_op.alter_column('rate', nullable=False)

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