"""fix_project_members_role_id_after_move

Revision ID: 0265
Revises: 0264
Create Date: 2025-02-05 13:16:17.623883

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


# revision identifiers, used by Alembic.
revision = '0265'
down_revision = '0264'
branch_labels = None
depends_on = None


def upgrade():
    op.execute("""
        UPDATE project_members pm
        SET role_id = (
            SELECT r2.id FROM roles r2 WHERE (r.builtin = r2.builtin OR r.name = r2.name)
            AND r2.owner_id = p.owner_id
        )
        FROM projects p, roles r
        WHERE pm.project_id = p.id AND r.id = pm.role_id AND p.owner_id != r.owner_id
    """)


def downgrade():
    pass