"""Create a last updated time column for scores.

Revision ID: ad911b666f22
Revises: b09f1e39c951
Create Date: 2018-02-15 21:29:02.735626

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text

# revision identifiers, used by Alembic.
revision = 'ad911b666f22'
down_revision = 'b09f1e39c951'
branch_labels = None
depends_on = None


def upgrade():
    conn = op.get_bind()

    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('score', sa.Column('update', sa.Integer(), nullable=False))
    op.create_index(op.f('ix_score_update'), 'score', ['update'], unique=False)
    # ### end Alembic commands ###

    sql = 'SELECT userid, musicid, timestamp FROM score'
    results = conn.execute(text(sql), {})
    for result in results:
        sql = (
            'UPDATE score SET `update` = ' +
            '(SELECT IFNULL(MAX(timestamp), :timestamp) FROM score_history WHERE score_history.userid = :userid AND score_history.musicid = :musicid) ' +
            'WHERE score.userid = :userid AND score.musicid = :musicid'
        )
        conn.execute(
            text(sql),
            {
                'userid': result['userid'],
                'musicid': result['musicid'],
                'timestamp': result['timestamp'],
            },
        )


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f('ix_score_update'), table_name='score')
    op.drop_column('score', 'update')
    # ### end Alembic commands ###
