"""attribute_pii

Revision: 0130
Revision ID: 384360aef2d6
Revises: 6e7bf3fa1d3
Create Date: 2018-05-04 17:37:20.524983

"""

# revision identifiers, used by Alembic.
revision = '384360aef2d6'
down_revision = '6e7bf3fa1d3'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa


def upgrade():
    op.add_column('attributes', sa.Column('is_pii', sa.Boolean(), nullable=True))
    op.create_index(op.f('ix_attributes_is_pii'), 'attributes', ['is_pii'], unique=False)
    op.execute("UPDATE attributes SET is_pii = false")

    op.add_column('projects', sa.Column('pii_identifier_attribute_id', sa.Integer(), nullable=True))
    op.create_foreign_key(None, 'projects', 'attributes', ['pii_identifier_attribute_id'], ['id'])

    op.execute("""
        UPDATE role_permissions SET actions = array_append(actions, 'MANAGE_PII_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 @> '{"MANAGE_PII_DATA"}'::varchar[])
    """)


def downgrade():
    op.drop_column('attributes', 'is_pii')
    op.drop_column('projects', 'pii_identifier_attribute_id')
