"""Review last modified time.

Revision ID: f689674e1c74
Revises: 1d24cba19e40
Create Date: 2020-06-18 15:50:17.494954

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from models.Review import Review

# revision identifiers, used by Alembic.
revision = 'f689674e1c74'
down_revision = '1d24cba19e40'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('review', sa.Column('review_last_modified_time', sa.DateTime(), nullable=False,
                                      server_default=sa.func.current_timestamp()))

    conn = op.get_bind()
    query = 'select {0} from {1}'.format('user_id, entity_id, review_time', 'review')
    res = conn.execute(query)
    update_dict = {}
    for columns in res:
        update_dict['review_last_modified_time'] = columns[2]
        conn.execute(
            Review.__table__.update().where(
                Review.__table__.c['user_id'] == columns[0]
            ).where(
                Review.__table__.c['entity_id'] == columns[1]
            ).values(**update_dict)
        )

    op.drop_column('review', 'review_time')
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('review', sa.Column('review_time', mysql.DATETIME(), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False))
    op.drop_column('review', 'review_last_modified_time')
    # ### end Alembic commands ###
