"""relationships_v2

Revision: 0204
Revision ID: e2464817d291
Revises: 397b2cb08fff
Create Date: 2021-01-28 09:40:47.009138

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


# revision identifiers, used by Alembic.
revision = 'e2464817d291'
down_revision = '397b2cb08fff'
branch_labels = None
depends_on = None


attributes = sa.Table(
    'attributes',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('type_name', sa.String),
    sa.Column('options', sa.PickleType)
)

cards = sa.Table(
    'cards',
    sa.MetaData(),
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('project_id', sa.Integer),
    sa.Column('parent_id', sa.Integer),
    sa.Column('title', sa.String)
)


def upgrade():
    op.execute("""
        UPDATE card_attributes
        SET value = jsonb_path_query_array(value, '$[*] ? (@.reversed == false).connected_card')
        WHERE type_name = 'relationships'
    """)

    op.execute("""
        DELETE FROM card_attributes
        WHERE type_name = 'relationships' AND jsonb_array_length(value) = 0
    """)

    conn = op.get_bind()
    q = select([attributes]).where(attributes.c.type_name == 'card')
    for attr in conn.execute(q):
        if not attr.options or not attr.options.get('card'):
            continue
        card = conn.execute(select([cards]).where(cards.c.id==attr.options['card'])).fetchone()
        if card and not card.parent_id:
            kql = 'project = "%s"' % card.title
        else:
            kql = 'parent = %s' % (card.id if card else attr.options['card'])
        conn.execute(attributes.update().where(attributes.c.id==attr.id).values(options={'search': kql}))

    op.execute("UPDATE cards SET cache_id = generate_cache_id(id) WHERE id IN (SELECT card_id FROM card_attributes WHERE type_name='relationships')")



def downgrade():
    pass
