"""import_export_role

Revision: 0169
Revision ID: 21cd415ba55b
Revises: 2212e3bc7f5f
Create Date: 2019-07-03 18:36:57.078155

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


# revision identifiers, used by Alembic.
revision = '21cd415ba55b'
down_revision = '2212e3bc7f5f'
branch_labels = None
depends_on = None


def upgrade():
    op.execute("""
        UPDATE role_permissions SET actions = array_append(actions, 'IMPORT_DATA')
        FROM roles WHERE roles.id = role_permissions.role_id
        AND roles.builtin = 'ADMIN'
        AND role_permissions.object_type = 'project'
        AND role_permissions.object_id IS NULL
        AND NOT (role_permissions.actions @> '{"IMPORT_DATA"}'::varchar[])
    """)

    op.execute("""
        UPDATE role_permissions SET actions = array_append(actions, 'EXPORT_DATA')
        FROM roles WHERE roles.id = role_permissions.role_id
        AND roles.builtin = 'ADMIN'
        AND role_permissions.object_type = 'project'
        AND role_permissions.object_id IS NULL
        AND NOT (role_permissions.actions @> '{"EXPORT_DATA"}'::varchar[])
    """)

    op.execute("""
        UPDATE roles SET cache_id = uuid_generate_v4()
        WHERE roles.id IN (
            SELECT DISTINCT roles.id
            FROM roles, role_permissions
            WHERE role_permissions.role_id = roles.id
            AND roles.builtin = 'ADMIN'
            AND role_permissions.object_type = 'project'
            AND role_permissions.object_id IS NULL
            AND (role_permissions.actions @> '{"IMPORT_DATA"}'::varchar[])
        )
    """)

    op.execute("""
        UPDATE projects SET members_cache_id = uuid_generate_v4() FROM organizations, roles, role_permissions
        WHERE organizations.id = projects.owner_id
            AND roles.owner_id = organizations.id
            AND roles.builtin = 'ADMIN'
            AND role_permissions.role_id = roles.id
            AND role_permissions.object_type = 'project'
            AND role_permissions.object_id IS NULL
            AND (role_permissions.actions @> '{"IMPORT_DATA"}'::varchar[])
    """)


def downgrade():
    pass
