"""build_tsvector

Revision: 0188
Revision ID: 68d34c581b25
Revises: 24858bb4f862
Create Date: 2020-08-13 11:36:05.800234

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


# revision identifiers, used by Alembic.
revision = '68d34c581b25'
down_revision = '24858bb4f862'
branch_labels = None
depends_on = None


def upgrade():
    # some old installations may not have the good build_tsvector() function
    # we need to make sure that the schema is mentionned in unaccent() under postgresql12

    op.execute("""
        CREATE OR REPLACE FUNCTION build_tsvector(content text) RETURNS tsvector
        AS
        $BODY$
            SELECT to_tsvector(public.unaccent('public.unaccent', left(content, 500000)));
        $BODY$
        LANGUAGE sql
        IMMUTABLE;
    """)

    op.execute("""DROP INDEX IF EXISTS ix_cards_fulltext""")
    op.execute("""DROP INDEX IF EXISTS ix_card_attributes_fulltext""")
    op.execute("""DROP INDEX IF EXISTS ix_card_comments_fulltext""")

    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("""CREATE INDEX ix_card_comments_fulltext ON card_comments USING gin(build_tsvector(message))""")


def downgrade():
    pass
