"""`workflow_draft_varaibles` add `node_execution_id` column, add an index for `workflow_node_executions`.

Revision ID: 4474872b0ee6
Revises: 2adcbe1f5dfb
Create Date: 2025-06-06 14:24:44.213018

"""
from alembic import op
import models as models
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '4474872b0ee6'
down_revision = '2adcbe1f5dfb'
branch_labels = None
depends_on = None


def upgrade():
    # `CREATE INDEX CONCURRENTLY` cannot run within a transaction, so use the `autocommit_block`
    # context manager to wrap the index creation statement.
    # Reference:
    #
    # - https://www.postgresql.org/docs/current/sql-createindex.html#:~:text=Another%20difference%20is,CREATE%20INDEX%20CONCURRENTLY%20cannot.
    # - https://alembic.sqlalchemy.org/en/latest/api/runtime.html#alembic.runtime.migration.MigrationContext.autocommit_block
    with op.get_context().autocommit_block():
        op.create_index(
            op.f('workflow_node_executions_tenant_id_idx'),
            "workflow_node_executions",
            ['tenant_id', 'workflow_id', 'node_id', sa.literal_column('created_at DESC')],
            unique=False,
            postgresql_concurrently=True,
        )

    with op.batch_alter_table('workflow_draft_variables', schema=None) as batch_op:
        batch_op.add_column(sa.Column('node_execution_id', models.types.StringUUID(), nullable=True))
    # ### end Alembic commands ###


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

    # `DROP INDEX CONCURRENTLY` cannot run within a transaction, so use the `autocommit_block`
    # context manager to wrap the index creation statement.
    # Reference:
    #
    # - https://www.postgresql.org/docs/current/sql-createindex.html#:~:text=Another%20difference%20is,CREATE%20INDEX%20CONCURRENTLY%20cannot.
    # - https://alembic.sqlalchemy.org/en/latest/api/runtime.html#alembic.runtime.migration.MigrationContext.autocommit_block
    # `DROP INDEX CONCURRENTLY` cannot run within a transaction, so commit existing transactions first.
    # Reference:
    #
    # https://www.postgresql.org/docs/current/sql-createindex.html#:~:text=Another%20difference%20is,CREATE%20INDEX%20CONCURRENTLY%20cannot.
    with op.get_context().autocommit_block():
        op.drop_index(op.f('workflow_node_executions_tenant_id_idx'), postgresql_concurrently=True)

    with op.batch_alter_table('workflow_draft_variables', schema=None) as batch_op:
        batch_op.drop_column('node_execution_id')

    # ### end Alembic commands ###
