"""finished_at

Revision: 0054
Revision ID: 4b225430041e
Revises: 78a2be497a8
Create Date: 2016-03-21 18:03:16.448997

"""

# revision identifiers, used by Alembic.
revision = '4b225430041e'
down_revision = '78a2be497a8'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa


def upgrade():
    op.add_column('cards', sa.Column('finished_at', sa.DateTime(), nullable=True))
    op.create_index(op.f('ix_cards_finished_at'), 'cards', ['finished_at'], unique=False)
    op.execute("""
        update cards set finished_at = (select min(created_at) from card_change_history
        where state in ('completed', 'closed', 'dropped') and card_id = cards.id)
    """)


def downgrade():
    op.drop_index(op.f('ix_cards_finished_at'), table_name='cards')
    op.drop_column('cards', 'finished_at')
