"""combine-filetype-tables

Revision ID: 5c594d23709b
Revises: 0fcf578896f3
Create Date: 2016-11-01 18:22:26.985281

"""

# revision identifiers, used by Alembic.
revision = '5c594d23709b'
down_revision = '0fcf578896f3'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa


def upgrade(engine_name):
    globals()["upgrade_%s" % engine_name]()


def downgrade(engine_name):
    globals()["downgrade_%s" % engine_name]()





def upgrade_data_broker():

    # add file_order column so we can phase out the file_type_validation table
    op.add_column('file_type', sa.Column('file_order', sa.Integer(), nullable=True))

    # populate file_order column (it's easy enough b/c currently the order =
    # the file_type_id key). E and F files don't get a file_order b/c they
    # aren't involved in cross-file-validations

    op.execute("""
                UPDATE file_type
                SET file_order = file_type_id
                WHERE letter_name IN ('A', 'B', 'C', 'D1', 'D2')
            """)

    # drop foreign keys to file_type_validation table and re-create them
    # as references to file_type table
    op.drop_constraint('file_columns_file_id_fkey', 'file_columns', type_='foreignkey')
    op.create_foreign_key('fk_file_column_file_type', 'file_columns', 'file_type', ['file_id'], ['file_type_id'])
    op.drop_constraint('fk_file', 'rule_sql', type_='foreignkey')
    op.drop_constraint('fk_target_file', 'rule_sql', type_='foreignkey')
    op.create_foreign_key('fk_file', 'rule_sql', 'file_type', ['file_id'], ['file_type_id'])
    op.create_foreign_key('fk_target_file', 'rule_sql', 'file_type', ['target_file_id'], ['file_type_id'])


def downgrade_data_broker():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint('fk_target_file', 'rule_sql', type_='foreignkey')
    op.drop_constraint('fk_file', 'rule_sql', type_='foreignkey')
    op.create_foreign_key('fk_target_file', 'rule_sql', 'file_type_validation', ['target_file_id'], ['file_id'])
    op.create_foreign_key('fk_file', 'rule_sql', 'file_type_validation', ['file_id'], ['file_id'])
    op.drop_column('file_type', 'file_order')
    op.drop_constraint('fk_file_column_file_type', 'file_columns', type_='foreignkey')
    op.create_foreign_key('file_columns_file_id_fkey', 'file_columns', 'file_type_validation', ['file_id'], ['file_id'])
    ### end Alembic commands ###

