"""Add deployment column and change unique constraint on users to deployment/
email.

Revision ID: 1a45abbc3682
Revises: 50de7e70cdd0
Create Date: 2015-09-10 14:22:39.853006

"""

# revision identifiers, used by Alembic.
revision = '1a45abbc3682'
down_revision = '50de7e70cdd0'

from alembic import op
import sqlalchemy as sa
import yaml


def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('users', sa.Column('deployment', sa.String()))

    try:
        with open('/noi/app/config/local_config.yml', 'r') as config_file:
            noi_deploy = yaml.load(config_file).get('NOI_DEPLOY')
    except IOError:
        noi_deploy = '_default'

    #op.execute(User.update().values({'name': noi_deploy}))
    op.execute("UPDATE users SET deployment = '{}';".format(noi_deploy))

    # Prevent nulls in the column
    op.alter_column('users', sa.Column('deployment', sa.String(), nullable=False))

    op.drop_constraint(u'users_email_key', 'users', type_='unique')
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_unique_constraint(u'users_email_key', 'users', ['email'])
    op.drop_column('users', 'deployment')
    ### end Alembic commands ###
