# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2022-04-27 16:59
from __future__ import unicode_literals

from django.db import migrations
from django.db import models


class ConditionalConcurrentTextPatternIndex(migrations.AddIndex):

    def database_forwards(self, app_label, schema_editor, from_state, to_state):
        if "postgresql" in schema_editor.connection.vendor:
            # Most of this code is vendored from here:
            # https://github.com/django/django/blob/stable/1.11.x/django/db/models/indexes.py#L48
            # With some tweaks to add the index concurrently, only if it doesn't already exist,
            # and with text_pattern_ops
            model = to_state.apps.get_model(app_label, self.model_name)
            quote_name = schema_editor.quote_name
            sql_template = "CREATE INDEX CONCURRENTLY IF NOT EXISTS {index_name} ON {table_name} ({columns} text_pattern_ops){extra}"
            fields = [model._meta.get_field(field_name) for field_name, _ in self.index.fields_orders]
            tablespace_sql = schema_editor._get_index_tablespace_sql(model, fields)
            quote_name = schema_editor.quote_name
            columns = [
                ('%s %s' % (quote_name(field.column), order)).strip()
                for field, (_, order) in zip(fields, self.index.fields_orders)
            ]
            schema_editor.execute(
                sql_template.format(
                    index_name=quote_name(self.index.name),
                    table_name=quote_name(model._meta.db_table),
                    columns=', '.join(columns),
                    extra=tablespace_sql
                )
            )
        else:
            super(ConditionalConcurrentTextPatternIndex, self).database_forwards(app_label, schema_editor, from_state, to_state)


class Migration(migrations.Migration):
    # In order to generate an index concurrently, we cannot run it inside a transaction.
    atomic = False

    dependencies = [
        ('morango', '0020_postgres_fix_nullable'),
    ]

    operations = [
        ConditionalConcurrentTextPatternIndex(
            model_name='store',
            index=models.Index(fields=['partition'], name='idx_morango_store_partition'),
        )
    ]
