"""add missing unique constraints

Revision ID: fb87feaaa094
Revises: 1cb44194db49
Create Date: 2021-02-03 19:02:51.347109

"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils


# revision identifiers, used by Alembic.
revision = 'fb87feaaa094'
down_revision = '1cb44194db49'
branch_labels = None
depends_on = None


def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    from zou.app.models.entity import Entity, EntityLink
    links = EntityLink.query.all()
    out_map = {}
    link_map = {}
    for link in links:
        key = str(link.entity_in_id) + "|" + str(link.entity_out_id)
        if  key not in out_map:
            out_map[key] = 0
        out_map[key] += 1
        link_map[key] = link
    for key, number in out_map.items():
        [in_link_id, out_link_id] = key.split("|")
        if number > 2:
            link.delete()
    #op.create_unique_constraint('entity_link_uc', 'entity_link', ['entity_in_id', 'entity_out_id'])
    op.create_unique_constraint('schedule_item_uc', 'schedule_item', ['project_id', 'task_type_id', 'object_id'])
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint('schedule_item_uc', 'schedule_item', type_='unique')
    op.drop_constraint('entity_link_uc', 'entity_link', type_='unique')
    # ### end Alembic commands ###

"""add missing unique constraints

Revision ID: fb87feaaa094
Revises: 1cb44194db49
Create Date: 2021-02-03 19:02:51.347109

"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils


# revision identifiers, used by Alembic.
revision = 'fb87feaaa094'
down_revision = '1cb44194db49'
branch_labels = None
depends_on = None


def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_unique_constraint('entity_link_uc', 'entity_link', ['entity_in_id', 'entity_out_id'])
    op.create_unique_constraint('schedule_item_uc', 'schedule_item', ['project_id', 'task_type_id', 'object_id'])
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint('schedule_item_uc', 'schedule_item', type_='unique')
    op.drop_constraint('entity_link_uc', 'entity_link', type_='unique')
    # ### end Alembic commands ###

Fix unique constraint migration patch