"""scope_card_group_position

Revision: 0135
Revision ID: 49d68aabe6a1
Revises: 11fab9822bf6
Create Date: 2018-06-28 12:01:16.701330

"""

# revision identifiers, used by Alembic.
revision = '49d68aabe6a1'
down_revision = '11fab9822bf6'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa


def upgrade():
    op.execute("""
        WITH positions as (
            SELECT group_id, card_id, row_number() OVER (partition by group_id, cards.parent_id order by position) AS p
            FROM card_groups_cards JOIN cards ON cards.id = card_groups_cards.card_id
            WHERE NOT cards.is_archived
        ) UPDATE card_groups_cards SET position = positions.p - 1 FROM positions
        WHERE positions.group_id = card_groups_cards.group_id AND positions.card_id = card_groups_cards.card_id
    """)

    op.execute("""
        UPDATE cards SET cache_id = uuid_generate_v4() FROM card_groups_cards cgt WHERE cgt.card_id = cards.id
    """)

    op.execute("""
        WITH positions as (
            SELECT id, row_number() OVER (partition by group_type_id, parent_id order by position) AS p
            FROM card_groups WHERE NOT is_archived
        ) UPDATE card_groups SET position = positions.p - 1 FROM positions
        WHERE positions.id = card_groups.id
    """)


def downgrade():
    pass
