"""Add event_id to Announcements and sponsor Levels

Revision ID: 4a435efab65
Revises: 177a65486a0
Create Date: 2015-04-28 00:07:35.365746

"""

# revision identifiers, used by Alembic.
revision = '4a435efab65'
down_revision = '4fb5af01b5'

from alembic import op
import sqlalchemy as sa


def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('announcements', sa.Column('event_id', sa.Integer(), nullable=True))
    op.create_foreign_key(op.f('announcements_event_id_fkey'), 'announcements', 'events', ['event_id'], ['id'])
    op.add_column('sponsor_levels', sa.Column('event_id', sa.Integer(), nullable=True))
    op.create_foreign_key(op.f('sponsor_levels_event_id_fkey'), 'sponsor_levels', 'events', ['event_id'], ['id'])
    ### end Alembic commands ###

    # Begin data migration
    op.execute(
        'UPDATE announcements SET event_id=('
        'SELECT id FROM events ORDER BY id DESC LIMIT 1'
        ')'
    )
    op.execute(
        'UPDATE sponsor_levels SET event_id=('
        'SELECT id FROM events ORDER BY id DESC LIMIT 1'
        ')'
    )
    # End data migration
    
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('announcements', 'event_id',
               existing_type=sa.INTEGER(),
               nullable=False)
    op.alter_column('sponsor_levels', 'event_id',
               existing_type=sa.INTEGER(),
               nullable=False)
    ### end Alembic commands ###


def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('sponsor_levels', 'event_id',
               existing_type=sa.INTEGER(),
               nullable=True)
    op.alter_column('announcements', 'event_id',
               existing_type=sa.INTEGER(),
               nullable=True)
    op.drop_constraint(op.f('sponsor_levels_event_id_fkey'), 'sponsor_levels', type_='foreignkey')
    op.drop_column('sponsor_levels', 'event_id')
    op.drop_constraint(op.f('announcements_event_id_fkey'), 'announcements', type_='foreignkey')
    op.drop_column('announcements', 'event_id')
    ### end Alembic commands ###
