"""attribute_options_jsonb

Revision: 0226
Revision ID: b069c965f0d3
Revises: f04a85eeb070
Create Date: 2021-11-24 11:19:46.530889

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


# revision identifiers, used by Alembic.
revision = 'b069c965f0d3'
down_revision = 'f04a85eeb070'
branch_labels = None
depends_on = None



attributes_table = sa.Table(
    'attributes',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('options', postgresql.JSONB, primary_key=True),
    sa.Column('pickled_options', sa.PickleType, primary_key=True)
)


def upgrade():
    op.alter_column('attributes', 'options', new_column_name='pickled_options')
    op.add_column('attributes', sa.Column('options', postgresql.JSONB(), nullable=True))
    op.create_index(op.f('ix_attributes_options'), 'attributes', ['options'], unique=False, postgresql_using='gin')

    conn = op.get_bind()
    updates = []
    for attr in conn.execute(attributes_table.select()):
        if attr.pickled_options:
            updates.append({'aid': attr.id, 'options': attr.pickled_options})

    if updates:
        conn.execute(attributes_table.update().where(attributes_table.c.id==sa.bindparam('aid')).values(
            options=sa.bindparam('options')), updates)


def downgrade():
    op.drop_column('attributes', 'options')
    op.add_column('attributes', sa.Column('options', sa.PickleType(), nullable=True))
