"""attr_positions

Revision: 0079
Revision ID: 369797b75a28
Revises: 4e9a229614fb
Create Date: 2016-09-12 16:31:22.303423

"""

# revision identifiers, used by Alembic.
revision = '369797b75a28'
down_revision = '4e9a229614fb'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql


def upgrade():
    op.create_table('attribute_positions',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('attribute_id', sa.Integer(), nullable=False),
        sa.Column('namespace', sa.String(), nullable=True),
        sa.Column('container', sa.String(), nullable=True),
        sa.Column('relative_to', sa.Integer(), nullable=True),
        sa.Column('position', sa.Integer(), nullable=True),
        sa.ForeignKeyConstraint(['attribute_id'], ['attributes.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_attribute_positions_attribute_id'), 'attribute_positions', ['attribute_id'], unique=False)
    op.create_index(op.f('ix_attribute_positions_namespace_container_relative_to'), 'attribute_positions', ['namespace', 'container', 'relative_to'], unique=False)

    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 positions.id = attributes.id
    """)


def downgrade():
    op.drop_table('attribute_positions')