"""ScoDoc 9.0.51: add unicity constraint on notes_moduleimpl_inscription

Revision ID: d74b4e16fb3c
Revises: f86c013c9fbd
Create Date: 2021-10-09 20:08:50.927330

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.orm import sessionmaker  # added by ev


# revision identifiers, used by Alembic.
revision = "d74b4e16fb3c"
down_revision = "f86c013c9fbd"
branch_labels = None
depends_on = None

Session = sessionmaker()


def upgrade():
    # Added by ev: remove duplicates
    bind = op.get_bind()
    session = Session(bind=bind)
    session.execute(
        """
    DELETE FROM notes_moduleimpl_inscription i1
    USING notes_moduleimpl_inscription i2
    WHERE i1.id < i2.id
    AND i1.moduleimpl_id = i2.moduleimpl_id
    AND i1.etudid = i2.etudid;
    """
    )

    # ### commands auto generated by Alembic - please adjust! ###
    op.create_unique_constraint(
        None, "notes_moduleimpl_inscription", ["moduleimpl_id", "etudid"]
    )
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, "notes_moduleimpl_inscription", type_="unique")
    # ### end Alembic commands ###
