"""Add jsonb fields

Revision ID: 0006_add_jsonb_fields
Revises: 0005
Create Date: 2023-05-03 11:48:01.679222

"""

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = "0006_add_jsonb_fields"
down_revision = "0005"
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column(
        "items",
        "data",
        existing_type=postgresql.JSON(astext_type=sa.Text()),
        type_=postgresql.JSONB(astext_type=sa.Text()),
        existing_nullable=False,
    )
    op.create_index(op.f("ix_items_hash"), "items", ["hash"], unique=False)
    op.alter_column(
        "tasks",
        "p_item",
        existing_type=postgresql.JSON(astext_type=sa.Text()),
        type_=postgresql.JSONB(astext_type=sa.Text()),
        existing_nullable=False,
    )
    op.execute("CREATE INDEX ix_tasks_p_item_hash ON tasks ((p_item->>'hash'), created_at DESC)")
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column(
        "tasks",
        "p_item",
        existing_type=postgresql.JSONB(astext_type=sa.Text()),
        type_=postgresql.JSON(astext_type=sa.Text()),
        existing_nullable=False,
    )
    op.drop_index(op.f("ix_items_hash"), table_name="items")
    op.alter_column(
        "items",
        "data",
        existing_type=postgresql.JSONB(astext_type=sa.Text()),
        type_=postgresql.JSON(astext_type=sa.Text()),
        existing_nullable=False,
    )
    op.execute("DROP INDEX ix_tasks_p_item_hash")
    # ### end Alembic commands ###
