"""reindex_positions

Revision: 0136
Revision ID: 53e5e98f0381
Revises: 49d68aabe6a1
Create Date: 2018-06-30 15:05:17.016244

"""

# revision identifiers, used by Alembic.
revision = '53e5e98f0381'
down_revision = '49d68aabe6a1'
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
    """)


def downgrade():
    pass
