"""view_position

Revision: 0081
Revision ID: 4ae4624010e9
Revises: 30ad9d5dfff6
Create Date: 2017-02-06 22:02:12.685926

"""

# revision identifiers, used by Alembic.
revision = '4ae4624010e9'
down_revision = '30ad9d5dfff6'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa


def upgrade():
    op.add_column('views', sa.Column('position', sa.Integer(), nullable=True))
    op.create_index(op.f('ix_views_position'), 'views', ['position'], unique=False)
    op.execute("""
        WITH positions as (
            SELECT id, row_number() OVER (partition by project_id order by id) AS p
            FROM views
        ) UPDATE views SET position = positions.p - 1 FROM positions
        WHERE positions.id = views.id
    """)


def downgrade():
    op.drop_index(op.f('ix_views_position'), table_name='views')
    op.drop_column('views', 'position')
