# Generated by Django 3.0.4 on 2020-03-10 14:47

from django.db import migrations

FIELDS = (
    ("unit", "source"),
    ("unit", "target"),
    ("unit", "context"),
    ("unit", "note"),
    ("unit", "location"),
    ("suggestion", "target"),
    ("comment", "comment"),
    ("dictionary", "source"),
)

PG_TRGM = "CREATE INDEX {0}_{1}_fulltext ON trans_{0} USING GIN ({1} gin_trgm_ops)"
PG_DROP = "DROP INDEX {0}_{1}_fulltext"

MY_FTX = "CREATE FULLTEXT INDEX {0}_{1}_fulltext ON trans_{0}({1})"
MY_DROP = "ALTER TABLE trans_{0} DROP INDEX {0}_{1}_fulltext"


def create_index(apps, schema_editor):
    vendor = schema_editor.connection.vendor
    if vendor == "postgresql":
        # Install pg_trgm for trigram search and index
        cur = schema_editor.connection.cursor()
        cur.execute("SELECT * FROM pg_extension WHERE extname = 'pg_trgm'")
        if not cur.fetchone():
            schema_editor.execute("CREATE EXTENSION IF NOT EXISTS pg_trgm")

        # Create GIN trigram index on searched fields
        for table, field in FIELDS:
            schema_editor.execute(PG_TRGM.format(table, field))
    elif vendor == "mysql":
        for table, field in FIELDS:
            schema_editor.execute(MY_FTX.format(table, field))
    else:
        raise Exception("Unsupported database: {}".format(vendor))


def drop_index(apps, schema_editor):
    vendor = schema_editor.connection.vendor
    if vendor == "postgresql":
        for table, field in FIELDS:
            schema_editor.execute(PG_DROP.format(table, field))
    elif vendor == "mysql":
        for table, field in FIELDS:
            schema_editor.execute(MY_DROP.format(table, field))
    else:
        raise Exception("Unsupported database: {}".format(vendor))


class Migration(migrations.Migration):

    dependencies = [("trans", "0063_auto_20200305_2202")]

    # This can't be atomic on MySQL
    operations = [
        migrations.RunPython(create_index, drop_index, elidable=False, atomic=False)
    ]
