"""search

Revision: 0083
Revision ID: 57af91cc668a
Revises: 3ce9106c2680
Create Date: 2017-01-24 15:24:32.766888

"""

# revision identifiers, used by Alembic.
revision = '57af91cc668a'
down_revision = '3ce9106c2680'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql


def upgrade():
    op.create_index(op.f('ix_attributes_name_lower'), 'attributes', [sa.text('lower(name)')], unique=False)
    op.create_index(op.f('ix_card_models_name_lower'), 'card_models', [sa.text('lower(name)')], unique=False)
    op.create_index(op.f('ix_organizations_name_lower'), 'organizations', [sa.text('lower(name)')], unique=False)

    op.execute("""CREATE EXTENSION IF NOT EXISTS unaccent;""")
    op.execute("""
        CREATE OR REPLACE FUNCTION build_tsvector(content text) RETURNS tsvector
        AS
        $BODY$
            SELECT to_tsvector(unaccent(content));
        $BODY$
        LANGUAGE sql
        IMMUTABLE;
    """)

    op.execute("""CREATE INDEX ix_cards_fulltext ON cards USING gin(build_tsvector(title))""")
    op.execute("""CREATE INDEX ix_card_attributes_fulltext ON card_attributes USING gin(build_tsvector(unindexed_value))""")

    op.execute("""UPDATE views SET filter = regexp_replace(filter, 'due:([a-zA-Z0-9]+)', E'date?("\\\\1")', 'g')""")
    op.execute("""UPDATE views SET filter = regexp_replace(filter, 'state:(todo|doing|done)', E'state=\\\\1', 'g')""")
    op.execute("""UPDATE views SET filter = regexp_replace(filter, 'model:([a-zA-Z0-9]+)', E'model=\\\\1', 'g')""")
    op.execute("""UPDATE views SET filter = replace(filter, '#!active', 'is_in_active_group?()')""")


def downgrade():
    op.drop_index(op.f('ix_attributes_name_lower'), table_name='attributes')
    op.drop_index(op.f('ix_card_models_name_lower'), table_name='card_models')
    op.drop_index(op.f('ix_organizations_name_lower'), table_name='organizations')
    op.drop_index(op.f('ix_cards_fulltext'), table_name='cards')
    op.drop_index(op.f('ix_card_attributes_fulltext'), table_name='card_attributes')
    op.execute("DROP FUNCTION build_tsvector(text)")
    op.execute("DROP EXTENSION unaccent")