"""reset_attr_positions

Revision: 0094
Revision ID: 31367f4af05e
Revises: 248a52525842
Create Date: 2017-06-09 10:35:45.010815

"""

# revision identifiers, used by Alembic.
revision = '31367f4af05e'
down_revision = '248a52525842'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa


def upgrade():
    op.execute("""
        WITH positions as (
            SELECT id, row_number() OVER (partition by group_id, container order by position) AS p
            FROM attributes
        ) UPDATE attributes SET position = positions.p - 1 FROM positions
        WHERE attributes.id = positions.id
    """)

    op.execute("""
        DELETE FROM attribute_positions USING attributes, projects
        WHERE attributes.id = attribute_positions.attribute_id AND attributes.group_id = projects.attribute_group_id
    """)

    op.execute("""
        WITH positions as (
            SELECT ap.id, row_number() OVER (partition by a.group_id, ap.namespace, ap.container, ap.relative_to order by ap.position) AS p
            FROM attribute_positions ap JOIN attributes a ON a.id = ap.attribute_id
        ) UPDATE attribute_positions SET position = positions.p - 1 FROM positions
        WHERE attribute_positions.id = positions.id
    """)


def downgrade():
    pass
