"""update rule fields

Revision ID: aa56852fa76d
Revises: f0a507afabd4
Create Date: 2021-04-12 19:53:48.615218+00:00

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text

# revision identifiers, used by Alembic.
revision = 'aa56852fa76d'
down_revision = 'f0a507afabd4'
branch_labels = None
depends_on = None


def constraint_exists(constraint_name):
    connection = op.get_bind()
    result = connection.execute(
        text("""
            SELECT exists(
                SELECT 1
                from pg_catalog.pg_constraint
                where conname = :constraint_name
            ) as exists """
        ), **{
            'constraint_name': constraint_name,
        }
    ).first()

    return result.exists


def column_exists(table_name, column_name):
    connection = op.get_bind()
    result = connection.execute(
        text("""
            SELECT exists(
                SELECT 1
                FROM information_schema.columns
                WHERE table_name = :table_name
                    AND column_name = :column_name
            ) as exists """
        ), **{
            'table_name': table_name,
            'column_name': column_name,
        }
    ).first()
    return result.exists


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    if not column_exists('action', 'description'):
        op.add_column('action', sa.Column('description', sa.String(), nullable=False))
    op.drop_constraint('condition_rule_id_fkey', 'condition', type_='foreignkey')
    op.create_foreign_key('condition_rule_id_fkey', 'condition', 'rule', ['rule_id'], ['id'], ondelete='CASCADE')
    if not column_exists('rule', 'description'):
        op.add_column('rule', sa.Column('description', sa.String(), nullable=False))
    if not column_exists('rule', 'name'):
        op.add_column('rule', sa.Column('name', sa.String(), nullable=False))
    if not constraint_exists('ux_rule_name'):
        op.create_unique_constraint('ux_rule_name', 'rule', ['name'])
    if column_exists('rule', 'object'):
        op.drop_column('rule', 'object')
    if not constraint_exists('rule_action_uc'):
        op.create_unique_constraint('rule_action_uc', 'rule_action', ['rule_id', 'action_id'])
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###

    # several items could have been created 'conditionally' by upgrade()
    # so at this point their presence doesn't tell whether they was created by this script or not
    # therefore don't do anything to reverse them
    # a reversion operation does not apply if items weren't created or deleted by this script

    # op.drop_constraint('rule_action_uc', 'rule_action', type_='unique')
    # op.add_column('rule', sa.Column('object', postgresql.JSONB(astext_type=sa.Text()), autoincrement=False, nullable=False))
    # op.drop_constraint('ux_rule_name', 'rule', type_='unique')
    # op.drop_column('rule', 'name')
    # op.drop_column('rule', 'description')
    op.drop_constraint('condition_rule_id_fkey', 'condition', type_='foreignkey')
    op.create_foreign_key('condition_rule_id_fkey', 'condition', 'rule', ['rule_id'], ['id'])
    # op.drop_column('action', 'description')
    # ### end Alembic commands ###
