""" Migrations
"""

# Generated by Django 3.2.10 on 2021-12-17 21:34

import django.contrib.postgres.indexes
import django.contrib.postgres.search
from django.db import migrations

from django.conf import settings
from core_main_app.utils.databases.backend import uses_postgresql_backend


class Migration(migrations.Migration):
    """Migration"""

    dependencies = [
        ("core_main_app", "0002_site_update"),
    ]

    operations = [
        migrations.AddField(
            model_name="data",
            name="vector_column",
            field=django.contrib.postgres.search.SearchVectorField(null=True),
        ),
        migrations.AddIndex(
            model_name="data",
            index=django.contrib.postgres.indexes.GinIndex(
                fields=["vector_column"], name="core_main_a_vector__449df8_gin"
            ),
        ),
    ]
    if uses_postgresql_backend() and not settings.MONGODB_INDEXING:
        operations.append(
            migrations.RunSQL(
                sql="""
                  CREATE OR REPLACE FUNCTION update_dict_content_tsvector() RETURNS trigger AS $$
                  BEGIN
                    NEW."vector_column" :=
                      to_tsvector('english', NEW.dict_content::jsonb);
                    RETURN NEW;
                  END;
                  $$ LANGUAGE plpgsql;

                  CREATE TRIGGER vector_column_trigger
                  BEFORE INSERT OR UPDATE OF dict_content, vector_column
                  ON core_main_app_data
                  FOR EACH ROW EXECUTE PROCEDURE
                  update_dict_content_tsvector();
                  UPDATE core_main_app_data SET vector_column = NULL;
                """,
                reverse_sql="""
                  DROP TRIGGER IF EXISTS vector_column_trigger
                  ON core_main_app_data;
                """,
            )
        )
