"""fix_view_categories_after_copy_bug

Revision: 0244
Revision ID: 3dc5ebfeecea
Revises: aa02a8f6f3b1
Create Date: 2022-09-15 13:17:50.871121

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


# revision identifiers, used by Alembic.
revision = '3dc5ebfeecea'
down_revision = 'aa02a8f6f3b1'
branch_labels = None
depends_on = None


def upgrade():
    op.execute("""
        UPDATE views SET category_id = null
        WHERE category_id IS NOT NULL AND category_id NOT IN (SELECT id FROM view_categories WHERE project_id = views.project_id)
    """)

    op.execute("""
        WITH positions as (
            SELECT id, row_number() OVER (partition by project_id, category_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
