"""Add run metadata and tag index [4d5524b92a30].

Revision ID: 4d5524b92a30
Revises: 0.73.0
Create Date: 2025-01-30 11:30:36.736452

"""

from alembic import op
from sqlalchemy import inspect

# revision identifiers, used by Alembic.
revision = "4d5524b92a30"
down_revision = "0.73.0"
branch_labels = None
depends_on = None


def upgrade() -> None:
    """Upgrade database schema and/or data, creating a new revision."""
    connection = op.get_bind()

    inspector = inspect(connection)
    for index in inspector.get_indexes("run_metadata_resource"):
        # This index was manually added to some databases to improve the
        # speed and cache utilisation. In this case we simply return here and
        # don't continue with the migration.
        if (
            index["name"]
            == "ix_run_metadata_resource_resource_id_resource_type_run_metadata_"
        ):
            return

    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table(
        "run_metadata_resource", schema=None
    ) as batch_op:
        batch_op.create_index(
            "ix_run_metadata_resource_resource_id_resource_type_run_metadata_",
            ["resource_id", "resource_type", "run_metadata_id"],
            unique=False,
        )

    with op.batch_alter_table("tag_resource", schema=None) as batch_op:
        batch_op.create_index(
            "ix_tag_resource_resource_id_resource_type_tag_id",
            ["resource_id", "resource_type", "tag_id"],
            unique=False,
        )

    # ### end Alembic commands ###


def downgrade() -> None:
    """Downgrade database schema and/or data back to the previous revision."""
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table("tag_resource", schema=None) as batch_op:
        batch_op.drop_index("ix_tag_resource_resource_id_resource_type_tag_id")

    with op.batch_alter_table(
        "run_metadata_resource", schema=None
    ) as batch_op:
        batch_op.drop_index(
            "ix_run_metadata_resource_resource_id_resource_type_run_metadata_"
        )

    # ### end Alembic commands ###
