"""
Added unique constraint to username and unique constraint to user_role

Revision ID: ca449af8034c
Revises: 4aac5e0c6e66
Create Date: 2021-06-14 15:36:58.043814

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = "ca449af8034c"
down_revision = "4aac5e0c6e66"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    # First change - unique constraint to "username" column in "users" table
    if conn.dialect.name == "postgresql":
        op.create_unique_constraint("c_unique_users_username", "users", ["username"])
    else:
        with op.batch_alter_table(
            "users",
            table_args=(
                sa.UniqueConstraint("username", name="c_unique_users_username"),
            ),
        ) as batch_op:
            batch_op.alter_column("username", nullable=False)

    # Second change - unique constraint in "user_role" with "user_id" and "role_id"
    if conn.dialect.name == "postgresql":
        op.create_unique_constraint(
            "c_unique_user_role_user_id_role_id", "user_role", ["user_id", "role_id"]
        )
    else:
        with op.batch_alter_table(
            "user_role",
            table_args=(
                sa.UniqueConstraint(
                    "user_id", "role_id", name="c_unique_user_role_user_id_role_id"
                ),
            ),
        ) as batch_op:
            batch_op.alter_column("user_id", nullable=False)

    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    bind = op.get_bind()
    # First change - drop unique constraint on "username"
    if bind.engine.name == "postgresql":
        op.drop_constraint("c_unique_users_username", "users")
    else:
        with op.batch_alter_table("users") as batch_op:
            batch_op.drop_constraint("c_unique_users_username", type_="unique")

    # Second change - drop unique constraint on "user_role"
    if bind.engine.name == "postgresql":
        op.drop_constraint(
            "c_unique_user_role_user_id_role_id", "user_role", type_="unique"
        )
    else:
        with op.batch_alter_table("user_role") as batch_op:
            batch_op.drop_constraint(
                "c_unique_user_role_user_id_role_id", type_="unique"
            )

    # ### end Alembic commands ###
