"""Add new fields

Revision ID: d73f1a3bccf3
Revises: b3d0713c453e
Create Date: 2020-04-20 15:55:00.951631

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from caipirinha.migration_utils import is_sqlite

# revision identifiers, used by Alembic.
revision = 'd73f1a3bccf3'
down_revision = 'b3d0713c453e'
branch_labels = None
depends_on = None


def upgrade():
    if is_sqlite():
        with op.batch_alter_table('dashboard') as batch_op:
            batch_op.add_column(sa.Column('hash', sa.String(length=200), nullable=True))

        with op.batch_alter_table('visualization') as batch_op:
            batch_op.alter_column(column_name='job_id', nullable=True)
            batch_op.alter_column(column_name='suggested_width', nullable=True)
            batch_op.alter_column(column_name='task_id', nullable=True)
            batch_op.add_column(sa.Column('workflow_id', sa.Integer(), nullable=True))
    else:
        op.add_column('dashboard', sa.Column('hash', sa.String(length=200), nullable=True))
        op.add_column('visualization', sa.Column('workflow_id', sa.Integer(), nullable=True))
        op.alter_column('visualization', 'job_id',
                existing_type=mysql.INTEGER(display_width=11),
                nullable=True)
        op.alter_column('visualization', 'suggested_width',
                existing_type=mysql.INTEGER(display_width=11),
                nullable=True)
        op.alter_column('visualization', 'task_id',
                existing_type=mysql.VARCHAR(collation='utf8_unicode_ci', length=200),
                nullable=True)


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    if is_sqlite():
        with op.batch_alter_table('dashboard') as batch_op:
            batch_op.drop_column('hash')
        op.get_bind().execute('UPDATE visualization SET job_id = 0 WHERE job_id IS NULL')
        with op.batch_alter_table('visualization') as batch_op:
            batch_op.alter_column(column_name='job_id', nullable=False)
            batch_op.alter_column(column_name='suggested_width', nullable=False)
            batch_op.alter_column(column_name='task_id', nullable=False)
            batch_op.drop_column('workflow_id')
    else:
        op.alter_column('visualization', 'task_id',
                   existing_type=mysql.VARCHAR(collation='utf8_unicode_ci', length=200),
                   nullable=False)
        op.alter_column('visualization', 'job_id',
                   existing_type=mysql.INTEGER(display_width=11),
                   nullable=False)
        op.alter_column('visualization', 'suggested_width',
                   existing_type=mysql.INTEGER(display_width=11),
                   nullable=False)
        op.drop_column('visualization', 'workflow_id')
        op.drop_column('dashboard', 'hash')
