"""card_position

Revision: 0181
Revision ID: 27a56466f9a7
Revises: 175395377f47
Create Date: 2020-01-06 11:26:47.187268

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


# revision identifiers, used by Alembic.
revision = '27a56466f9a7'
down_revision = '175395377f47'
branch_labels = None
depends_on = None


def upgrade():
    op.add_column('cards', sa.Column('position', sa.Integer(), nullable=True))
    op.create_index(op.f('ix_cards_position'), 'cards', ['position'], unique=False)

    op.execute("""
        WITH positions as (
            SELECT id, row_number() OVER (partition by project_id order by id) AS p
            FROM cards
        ) UPDATE cards SET position = positions.p - 1 FROM positions
        WHERE positions.id = cards.id
    """)


def downgrade():
    op.drop_column('cards', 'position')
