"""fix_parents_ids

Revision: 0229
Revision ID: 9a7f12dce0ad
Revises: ad80214e4b12
Create Date: 2022-02-25 16:22:10.965530

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


# revision identifiers, used by Alembic.
revision = '9a7f12dce0ad'
down_revision = 'ad80214e4b12'
branch_labels = None
depends_on = None


def upgrade():
    op.execute("""
        WITH
        RECURSIVE recompute AS
        (
            -- Anchor
            SELECT id "origin_id", 1 "level", parent_id, array[parent_id] "pids"
            FROM cards
            WHERE parent_id IS NOT NULL

            UNION ALL

            -- Recursive Member
            SELECT r.origin_id, r.level+1, c.parent_id, array[c.parent_id]||r.pids
            FROM cards c
            JOIN recompute r ON c.id = r.parent_id
            WHERE c.parent_id IS NOT NULL
        ),

        levels AS
        (
            SELECT origin_id, max(level) "max"
            FROM recompute
            GROUP BY origin_id
        ),

        new_parents AS
        (
            SELECT r.origin_id "id", r.pids
            FROM recompute r
            JOIN levels l ON l.origin_id = r.origin_id
            WHERE r.level = l.max
        )

        UPDATE cards c
        SET parents_ids = np.pids
        FROM new_parents np
        WHERE np.id = c.id
        AND np.pids != c.parents_ids;
    """)


def downgrade():
    pass
