"""fix_view_positions

Revision: 0231
Revision ID: 0ce8c01ee717
Revises: 4748ed576de4
Create Date: 2022-03-02 07:35:51.313938

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


# revision identifiers, used by Alembic.
revision = '0ce8c01ee717'
down_revision = '4748ed576de4'
branch_labels = None
depends_on = None


def upgrade():
    op.execute("""
        WITH positions as (
            SELECT id, row_number() OVER (partition by project_id order by position) AS p
            FROM views
            WHERE views.project_id IS NOT NULL
        ) UPDATE views SET position = positions.p - 1 FROM positions
        WHERE positions.id = views.id
    """)

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


def downgrade():
    pass
