"""Create table for extids.

Revision ID: e918fab0402d
Revises: 6e2ac7400610
Create Date: 2017-04-20 23:04:11.042442

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


# revision identifiers, used by Alembic.
revision = 'e918fab0402d'
down_revision = '6e2ac7400610'
branch_labels = None
depends_on = None


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

    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('extid',
    sa.Column('game', sa.String(length=32), nullable=False),
    sa.Column('extid', sa.Integer(), nullable=False),
    sa.Column('userid', sa.Integer(), nullable=False),
    sa.UniqueConstraint('extid'),
    sa.UniqueConstraint('game', 'userid', name='game_userid'),
    mysql_charset='utf8mb4'
    )
    # ### end Alembic commands ###

    # Now, move over extid from the refid table for each user/game series.
    sql = 'SELECT userid, game, extid FROM refid ORDER BY version DESC'
    results = conn.execute(text(sql), {})
    updates = {}
    for result in results:
        sql = 'INSERT INTO extid (userid, game, extid) VALUES (:userid, :game, :extid)'
        try:
            conn.execute(text(sql), {
                'userid': result['userid'],
                'game': result['game'],
                'extid': result['extid'],
            })
        except sa.exc.IntegrityError:
            pass


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('extid')
    # ### end Alembic commands ###
