"""reindex_positions

Revision: 0045
Revision ID: 34d8e77407
Revises: 21e56a0093b
Create Date: 2015-12-23 21:34:41.956525

"""

# revision identifiers, used by Alembic.
revision = '34d8e77407'
down_revision = '21e56a0093b'
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 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("""
        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
