"""Clean up cascading deletes and add triggers

Revision ID: e645774b4c62
Revises: c23b3ba12869
Create Date: 2023-03-17 11:14:04.032459

"""

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = "e645774b4c62"
down_revision = "c23b3ba12869"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint("compute_manager_log_manager_id_fkey", "compute_manager_log", type_="foreignkey")
    op.create_foreign_key(None, "compute_manager_log", "compute_manager", ["manager_id"], ["id"], ondelete="cascade")

    op.execute(
        sa.text(
            """
    CREATE OR REPLACE FUNCTION public.qca_base_record_delete()
    RETURNS trigger
    LANGUAGE plpgsql
    AS $_$
        BEGIN
          DELETE FROM base_record WHERE base_record.id = OLD.id;
          RETURN OLD;
        END
        $_$
    ;
        """
        )
    )

    op.execute(
        sa.text(
            "CREATE TRIGGER qca_gridoptimization_record_delete_base_tr AFTER DELETE ON public.gridoptimization_record FOR EACH ROW EXECUTE FUNCTION qca_base_record_delete();"
        )
    )
    op.execute(
        sa.text(
            "CREATE TRIGGER qca_manybody_record_delete_base_tr AFTER DELETE ON public.manybody_record FOR EACH ROW EXECUTE FUNCTION qca_base_record_delete();"
        )
    )
    op.execute(
        sa.text(
            "CREATE TRIGGER qca_neb_record_delete_base_tr AFTER DELETE ON public.neb_record FOR EACH ROW EXECUTE FUNCTION qca_base_record_delete();"
        )
    )
    op.execute(
        sa.text(
            "CREATE TRIGGER qca_optimization_record_delete_base_tr AFTER DELETE ON public.optimization_record FOR EACH ROW EXECUTE FUNCTION qca_base_record_delete();"
        )
    )
    op.execute(
        sa.text(
            "CREATE TRIGGER qca_reaction_record_delete_base_tr AFTER DELETE ON public.reaction_record FOR EACH ROW EXECUTE FUNCTION qca_base_record_delete();"
        )
    )
    op.execute(
        sa.text(
            "CREATE TRIGGER qca_singlepoint_record_delete_base_tr AFTER DELETE ON public.singlepoint_record FOR EACH ROW EXECUTE FUNCTION qca_base_record_delete();"
        )
    )
    op.execute(
        sa.text(
            "CREATE TRIGGER qca_torsiondrive_record_delete_base_tr AFTER DELETE ON public.torsiondrive_record FOR EACH ROW EXECUTE FUNCTION qca_base_record_delete();"
        )
    )

    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, "compute_manager_log", type_="foreignkey")
    op.create_foreign_key(
        "compute_manager_log_manager_id_fkey", "compute_manager_log", "compute_manager", ["manager_id"], ["id"]
    )
    # ### end Alembic commands ###
