"""Fix clock_entry_breaks PK.

Revision ID: dc2a1fb619b9
Revises: 8d73e2e0ae6d
Create Date: 2022-02-16 18:12:55.446000

"""
from alembic import op

from sqlalchemy import Column, String, Index, ForeignKeyConstraint, UniqueConstraint, DateTime, Boolean

# revision identifiers, used by Alembic.
revision = 'dc2a1fb619b9'
down_revision = '8d73e2e0ae6d'
branch_labels = None
depends_on = None

first_agent_version = '22.2.25'


def upgrade():
    """
    Use batch-operations to support sqlite. If you are modifying any tables with foreign keys, be sure to disable
    foreign keys while upgrading.

    > conn = op.get_bind()
    > try:
    >     conn.execute('PRAGMA foreign_keys = "0";')
    >     with op.batch_alter_table('table_name') as batch_op:
    >         pass
    > finally:
    >     conn.execute('PRAGMA foreign_keys = "0";')
    """
    connection = op.get_bind()
    try:
        with connection.begin():
            connection.execute('PRAGMA foreign_keys = "0";')

            op.create_table(
                'clock_entry_breaks_tmp',
                Column('clock_entry_id', String(64), primary_key=True),
                Column('id', String(64), primary_key=True),
                Column('start', DateTime, nullable=False),
                Column('end', DateTime, nullable=True),
                Column('paid', Boolean, nullable=False),
                ForeignKeyConstraint(
                    ['clock_entry_id'],
                    ['clock_entries.id'],
                    name="fk_clock_entry_breaks_clock_entries",
                    onupdate='cascade',
                    ondelete='cascade',
                ),
            )

            connection.execute(
                """
                insert into clock_entry_breaks_tmp (clock_entry_id, id, start, end, paid)
                     select clock_entry_id, id, start, end, paid
                     from clock_entry_breaks
                """
            )

        op.drop_table('clock_entry_breaks')
        op.rename_table('clock_entry_breaks_tmp', 'clock_entry_breaks')
    finally:
        connection.execute('PRAGMA foreign_keys = "1";')


def downgrade():
    """
    Downgrading could lose data since there could be data with conflicting IDs/PKs. No harm in leaving the correct PK
    in place.
    """
    pass

