"""Update unique constraint for secret

Revision ID: 90d978a8aef8
Revises: dfe49d040487
Create Date: 2023-07-19 09:54:52.174582

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.engine.reflection import Inspector


# revision identifiers, used by Alembic.
revision = '90d978a8aef8'
down_revision = 'dfe49d040487'
branch_labels = None
depends_on = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    try:
        bind = op.get_bind()
        insp = Inspector.from_engine(bind.engine)
        with op.batch_alter_table('secret', schema=None) as batch_op:
            unique_constraints = insp.get_unique_constraints('secret')
            for constraint in unique_constraints:
                batch_op.drop_constraint(constraint['name'], type_='unique')
    except ValueError:
        with op.batch_alter_table('secret', schema=None) as batch_op:
            batch_op.add_column(sa.Column('name_new', sa.String(length=255), nullable=True))
        with op.batch_alter_table('secret', schema=None) as batch_op:
            batch_op.execute('UPDATE secret SET name_new = name')
        with op.batch_alter_table('secret', schema=None) as batch_op:
            batch_op.drop_column('name')
            batch_op.add_column(sa.Column('name', sa.String(length=255), nullable=True))
        with op.batch_alter_table('secret', schema=None) as batch_op:
            batch_op.execute('UPDATE secret SET name = name_new')
        with op.batch_alter_table('secret', schema=None) as batch_op:
            batch_op.drop_column('name_new')
    
    with op.batch_alter_table('secret', schema=None) as batch_op:
        batch_op.create_unique_constraint('name_unique', columns=['name'])
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###
