"""org_files

Revision: 0063
Revision ID: 2a74262efd7d
Revises: 3ab6d84b6186
Create Date: 2016-06-24 11:05:23.286438

"""

# revision identifiers, used by Alembic.
revision = '2a74262efd7d'
down_revision = '3ab6d84b6186'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa


def upgrade():
    op.rename_table('card_files', 'files')

    org_files = op.create_table('organizations_files',
        sa.Column('file_id', sa.Integer(), nullable=False),
        sa.Column('org_id', sa.Integer(), nullable=False),
        sa.ForeignKeyConstraint(['file_id'], ['files.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['org_id'], ['organizations.id'], ondelete='CASCADE'),
        sa.UniqueConstraint('file_id', 'org_id')
    )

    op.execute("""INSERT INTO organizations_files (file_id, org_id) SELECT DISTINCT files.id, c.owner_id
        FROM files, card_attributes ca JOIN cards c ON c.id = ca.card_id
        WHERE json_build_array(files.id)::jsonb <@ ca.value AND ca.type_name = 'files'""")

    op.execute("UPDATE activities SET sub_object_type = 'File' WHERE sub_object_type = 'CardFile'")

    op.drop_table('cards_card_files')


def downgrade():
    pass
