"""daily cache locks

Revision ID: d09c37d50194
Revises: a7b74667f7d6
Create Date: 2019-07-22 19:18:12.969000

"""
from alembic import op
import logging
import sqlalchemy as sa

logger = logging.getLogger(__name__)

# revision identifiers, used by Alembic.
revision = 'd09c37d50194'
down_revision = 'a7b74667f7d6'
branch_labels = None
depends_on = None

first_agent_version = '19.8.7'


def upgrade():
    connection = op.get_bind()
    inspector = sa.inspect(connection)
    tables = set(inspector.get_table_names())
    if 'daily_cache_locks' in tables:
        logger.info("Table 'daily_cache_locks' already exists. Skipping its migration...")
    else:
        op.create_table(
            'daily_cache_locks',
            sa.Column('id', sa.Integer(), nullable=False, autoincrement=True),
            sa.Column('datatype', sa.String(length=11), nullable=False),
            sa.Column('store_id', sa.String(length=64), nullable=True),
            sa.Column('days_ago', sa.Integer(), nullable=False),
            sa.Column('created_at', sa.DateTime(), nullable=True),
            sa.PrimaryKeyConstraint(
                'id',
                has_autoincrement=True,
            ),
            sa.Index(
                'store_id_datatype_days_ago_idx',
                'store_id',
                'datatype',
                'days_ago',
            ),
            sa.Index(
                'created_at_idx',
                'created_at',
            ),
        )


def downgrade():
    op.drop_table('daily_cache_locks')
