"""form_fields

Revision: 0089
Revision ID: 6dac66a4490
Revises: 57c60056d090
Create Date: 2017-03-16 11:50:20.360600

"""

# revision identifiers, used by Alembic.
revision = '6dac66a4490'    
down_revision = '57c60056d090'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa


def upgrade():
    op.create_table('request_form_fields',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('request_form_id', sa.Integer(), nullable=True),
        sa.Column('label', sa.String(), nullable=True),
        sa.Column('description', sa.Text(), nullable=True),
        sa.Column('required', sa.Boolean(), nullable=True),
        sa.Column('attribute_id', sa.Integer(), nullable=True),
        sa.ForeignKeyConstraint(['request_form_id'], ['request_forms.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['attribute_id'], ['attributes.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_request_form_fields_request_form_id'), 'request_form_fields', ['request_form_id'], unique=False)

    op.execute("""
        INSERT INTO request_form_fields (request_form_id, label, required)
        SELECT id, coalesce(title_label, 'Title'), true FROM request_forms WHERE ask_title
    """)

    op.execute("""
        INSERT INTO request_form_fields (request_form_id, label, required, attribute_id)
        SELECT request_form_id, attributes.name, false, attribute_id
        FROM request_form_attributes JOIN attributes ON attributes.id = attribute_id ORDER BY id
    """)

    op.drop_column('request_forms', 'ask_title')
    op.drop_column('request_forms', 'title_label')
    op.drop_table('request_form_attributes')


def downgrade():
    pass
