"""empty message

Revision ID: 0015_fix_template_data
Revises: 0014_add_template_version
Create Date: 2016-05-16 13:55:27.179748

"""

# revision identifiers, used by Alembic.
revision = "0015_fix_template_data"
down_revision = "0014_add_template_version"

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql


def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.get_bind()
    query = (
        "update templates_history set created_by_id = "
        "(select created_by_id from templates where templates.id = templates_history.id) "
        "where created_by_id is null"
    )
    op.execute(query)
    op.execute("update templates_history set archived = False")
    op.alter_column("api_keys_history", "created_at", existing_type=postgresql.TIMESTAMP(), nullable=False)
    op.alter_column("api_keys_history", "created_by_id", existing_type=postgresql.UUID(), nullable=False)
    op.alter_column("templates_history", "archived", existing_type=sa.BOOLEAN(), nullable=False)
    op.alter_column("templates_history", "created_by_id", existing_type=postgresql.UUID(), nullable=False)
    ### end Alembic commands ###


def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.alter_column("templates_history", "created_by_id", existing_type=postgresql.UUID(), nullable=True)
    op.alter_column("templates_history", "archived", existing_type=sa.BOOLEAN(), nullable=True)
    op.alter_column("api_keys_history", "created_by_id", existing_type=postgresql.UUID(), nullable=True)
    op.alter_column("api_keys_history", "created_at", existing_type=postgresql.TIMESTAMP(), nullable=True)
    ### end Alembic commands ###
