"""fix_calais

Revision ID: 3c31bb0b27c9
Revises: d5b3bdd1d622
Create Date: 2022-06-23 10:48:27.787550

Pour réparer les bases auxquelles il manquerait le ref. de comp.: 
bug dit "de Calais"

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = "3c31bb0b27c9"
down_revision = "d5b3bdd1d622"
branch_labels = None
depends_on = None


# Voir https://stackoverflow.com/questions/24082542/check-if-a-table-column-exists-in-the-database-using-sqlalchemy-and-alembic
from sqlalchemy import inspect


def column_exists(table_name, column_name):
    bind = op.get_context().bind
    insp = inspect(bind)
    columns = insp.get_columns(table_name)
    return any(c["name"] == column_name for c in columns)


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    if not column_exists("apc_competence", "id_orebut"):
        op.add_column(
            "apc_competence", sa.Column("id_orebut", sa.Text(), nullable=True)
        )
        op.create_index(
            op.f("ix_apc_competence_id_orebut"),
            "apc_competence",
            ["id_orebut"],
            unique=False,
        )
        op.drop_constraint(
            "apc_competence_referentiel_id_titre_key", "apc_competence", type_="unique"
        )
    if not column_exists("apc_referentiel_competences", "annexe"):
        op.add_column(
            "apc_referentiel_competences", sa.Column("annexe", sa.Text(), nullable=True)
        )
    if not column_exists("apc_referentiel_competences", "type_structure"):
        op.add_column(
            "apc_referentiel_competences",
            sa.Column("type_structure", sa.Text(), nullable=True),
        )
    if not column_exists("apc_referentiel_competences", "type_departement"):
        op.add_column(
            "apc_referentiel_competences",
            sa.Column("type_departement", sa.Text(), nullable=True),
        )
    if not column_exists("apc_referentiel_competences", "version_orebut"):
        op.add_column(
            "apc_referentiel_competences",
            sa.Column("version_orebut", sa.Text(), nullable=True),
        )

    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###

    # ne fait rien ! ce script est idempotent
    pass
    # ### end Alembic commands ###
