"""Removing partitions, adding foreign keys

Revision ID: e445d703e60f
Revises: 686dbbd19b95
Create Date: 2018-03-05 14:29:47.883125

"""
from alembic import op

from sqlalchemy.exc import SQLAlchemyError

# revision identifiers, used by Alembic.
revision = 'e445d703e60f'
down_revision = '686dbbd19b95'


def upgrade():
    partitions = (
        'tags', 'resources', 'resource_properties', 'issues',
        'issue_properties', 'auditlog', 'logs', 'emails'
    )
    for table in partitions:
        try:
            op.execute('ALTER TABLE `{}` REMOVE PARTITIONING'.format(table))
        except SQLAlchemyError as ex:
            # Silently ignore errors about removing partitions from a table without partitions
            if str(ex).find('1505') != -1:
                pass

            raise

    # ### commands auto generated by Alembic - please adjust! ###
    op.create_foreign_key('fk_resource_mapping_child', 'resource_mappings', 'resources', ['child'], ['resource_id'], ondelete='CASCADE')
    op.create_foreign_key('fk_resource_mapping_parent', 'resource_mappings', 'resources', ['parent'], ['resource_id'], ondelete='CASCADE')
    op.create_foreign_key('fk_resource_property_resource_id', 'resource_properties', 'resources', ['resource_id'], ['resource_id'], ondelete='CASCADE')
    op.create_foreign_key('fk_resource_account_id', 'resources', 'accounts', ['account_id'], ['account_id'], ondelete='CASCADE')
    op.create_foreign_key('fk_resource_types_resource_type_id', 'resources', 'resource_types', ['resource_type_id'], ['resource_type_id'], ondelete='CASCADE')
    op.create_foreign_key('fk_tag_resource_id', 'tags', 'resources', ['resource_id'], ['resource_id'], ondelete='CASCADE')
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint('fk_tag_resource_id', 'tags', type_='foreignkey')
    op.drop_constraint('fk_resource_types_resource_type_id', 'resources', type_='foreignkey')
    op.drop_constraint('fk_resource_account_id', 'resources', type_='foreignkey')
    op.drop_constraint('fk_resource_property_resource_id', 'resource_properties', type_='foreignkey')
    op.drop_constraint('fk_resource_mapping_parent', 'resource_mappings', type_='foreignkey')
    op.drop_constraint('fk_resource_mapping_child', 'resource_mappings', type_='foreignkey')
    # ### end Alembic commands ###
