# Path: psqlextra/indexes/case_insensitive_unique_index.py
# class CaseInsensitiveUniqueIndex(Index):
#     sql_create_unique_index = (
#         "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s"
#     )
# 
#     def create_sql(self, model, schema_editor, using="", **kwargs):
#         statement = super().create_sql(model, schema_editor, using)
#         statement.template = self.sql_create_unique_index
# 
#         column_collection = statement.parts["columns"]
#         statement.parts["columns"] = ", ".join(
#             [
#                 "LOWER(%s)" % self._quote_column(column_collection, column, idx)
#                 for idx, column in enumerate(column_collection.columns)
#             ]
#         )
# 
#         return statement
# 
#     def deconstruct(self):
#         """Serializes the :see:CaseInsensitiveUniqueIndex for the migrations
#         file."""
#         _, args, kwargs = super().deconstruct()
#         path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
#         path = path.replace("django.db.models.indexes", "django.db.models")
# 
#         return path, args, kwargs
# 
#     @staticmethod
#     def _quote_column(column_collection, column, idx):
#         quoted_name = column_collection.quote_name(column)
#         try:
#             return quoted_name + column_collection.col_suffixes[idx]
#         except IndexError:
#             return column_collection.quote_name(column)
# 
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
#     """Base class for for taking advantage of PostgreSQL specific features."""
# 
#     class Meta:
#         abstract = True
#         base_manager_name = "objects"
# 
#     objects = PostgresManager()
# 
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
#     """Defines a fake model and creates it in the database."""
# 
#     model = define_fake_model(fields, model_base, meta_options)
# 
#     with connection.schema_editor() as schema_editor:
#         schema_editor.create_model(model)
# 
#     return model
# 
# Path: tests/migrations.py
# def apply_migration(operations, state=None, backwards: bool = False):
#     """Executes the specified migration operations using the specified schema
#     editor.
# 
#     Arguments:
#         operations:
#             The migration operations to execute.
# 
#         state:
#             The state state to use during the
#             migrations.
# 
#         backwards:
#             Whether to apply the operations
#             in reverse (backwards).
#     """
# 
#     state = state or migrations.state.ProjectState.from_apps(apps)
# 
#     class Migration(migrations.Migration):
#         pass
# 
#     Migration.operations = operations
# 
#     migration = Migration("migration", "tests")
#     executor = MigrationExecutor(connection)
# 
#     if not backwards:
#         executor.apply_migration(state, migration)
#     else:
#         executor.unapply_migration(state, migration)
# 
#     return migration
# 
# @contextmanager
# def filtered_schema_editor(*filters: List[str]):
#     """Gets a schema editor, but filters executed SQL statements based on the
#     specified text filters.
# 
#     Arguments:
#         filters:
#             List of strings to filter SQL
#             statements on.
#     """
# 
#     with connection.schema_editor() as schema_editor:
#         wrapper_for = schema_editor.execute
#         with mock.patch.object(
#             PostgresSchemaEditor, "execute", wraps=wrapper_for
#         ) as execute:
#             filter_results = {}
#             yield filter_results
# 
#     for filter_text in filters:
#         filter_results[filter_text] = [
#             call for call in execute.mock_calls if filter_text in str(call)
#         ]


import pytest
from django.db import IntegrityError, connection, models
from django.db.migrations import AddIndex, CreateModel
from psqlextra.indexes import CaseInsensitiveUniqueIndex
from psqlextra.models import PostgresModel
from .fake_model import get_fake_model
from .migrations import apply_migration, filtered_schema_editor
    with filtered_schema_editor("CREATE UNIQUE INDEX") as calls:
        apply_migration(ops)

    sql = str([call[0] for _, call, _ in calls["CREATE UNIQUE INDEX"]][0])
    expected_sql = 'CREATE UNIQUE INDEX "index1" ON "tests_mymodel" (LOWER("name"), LOWER("other_name"))'
    assert sql == expected_sql


def test_ciui():
    """Tests whether the case insensitive unique index works as expected."""

    index_1 = CaseInsensitiveUniqueIndex(fields=["name"], name="index1")

    model = get_fake_model(
        {"name": models.CharField(max_length=255)}, PostgresModel
    )

    with connection.schema_editor() as schema_editor:
        schema_editor.add_index(model, index_1)

    model.objects.create(name="henk")

    with pytest.raises(IntegrityError):
        model.objects.create(name="Henk")


def test_ciui_on_conflict():
    """Tests wether fields with a :see:CaseInsensitiveUniqueIndex can be used
    as a conflict target."""


# Path: psqlextra/indexes/case_insensitive_unique_index.py
# class CaseInsensitiveUniqueIndex(Index):
#     sql_create_unique_index = (
#         "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)%(extra)s"
#     )
# 
#     def create_sql(self, model, schema_editor, using="", **kwargs):
#         statement = super().create_sql(model, schema_editor, using)
#         statement.template = self.sql_create_unique_index
# 
#         column_collection = statement.parts["columns"]
#         statement.parts["columns"] = ", ".join(
#             [
#                 "LOWER(%s)" % self._quote_column(column_collection, column, idx)
#                 for idx, column in enumerate(column_collection.columns)
#             ]
#         )
# 
#         return statement
# 
#     def deconstruct(self):
#         """Serializes the :see:CaseInsensitiveUniqueIndex for the migrations
#         file."""
#         _, args, kwargs = super().deconstruct()
#         path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
#         path = path.replace("django.db.models.indexes", "django.db.models")
# 
#         return path, args, kwargs
# 
#     @staticmethod
#     def _quote_column(column_collection, column, idx):
#         quoted_name = column_collection.quote_name(column)
#         try:
#             return quoted_name + column_collection.col_suffixes[idx]
#         except IndexError:
#             return column_collection.quote_name(column)
# 
# Path: psqlextra/models/base.py
# class PostgresModel(models.Model):
#     """Base class for for taking advantage of PostgreSQL specific features."""
# 
#     class Meta:
#         abstract = True
#         base_manager_name = "objects"
# 
#     objects = PostgresManager()
# 
# Path: tests/fake_model.py
# def get_fake_model(fields=None, model_base=PostgresModel, meta_options={}):
#     """Defines a fake model and creates it in the database."""
# 
#     model = define_fake_model(fields, model_base, meta_options)
# 
#     with connection.schema_editor() as schema_editor:
#         schema_editor.create_model(model)
# 
#     return model
# 
# Path: tests/migrations.py
# def apply_migration(operations, state=None, backwards: bool = False):
#     """Executes the specified migration operations using the specified schema
#     editor.
# 
#     Arguments:
#         operations:
#             The migration operations to execute.
# 
#         state:
#             The state state to use during the
#             migrations.
# 
#         backwards:
#             Whether to apply the operations
#             in reverse (backwards).
#     """
# 
#     state = state or migrations.state.ProjectState.from_apps(apps)
# 
#     class Migration(migrations.Migration):
#         pass
# 
#     Migration.operations = operations
# 
#     migration = Migration("migration", "tests")
#     executor = MigrationExecutor(connection)
# 
#     if not backwards:
#         executor.apply_migration(state, migration)
#     else:
#         executor.unapply_migration(state, migration)
# 
#     return migration
# 
# @contextmanager
# def filtered_schema_editor(*filters: List[str]):
#     """Gets a schema editor, but filters executed SQL statements based on the
#     specified text filters.
# 
#     Arguments:
#         filters:
#             List of strings to filter SQL
#             statements on.
#     """
# 
#     with connection.schema_editor() as schema_editor:
#         wrapper_for = schema_editor.execute
#         with mock.patch.object(
#             PostgresSchemaEditor, "execute", wraps=wrapper_for
#         ) as execute:
#             filter_results = {}
#             yield filter_results
# 
#     for filter_text in filters:
#         filter_results[filter_text] = [
#             call for call in execute.mock_calls if filter_text in str(call)
#         ]


# Path: tests/test_case_insensitive_unique_index.py
import pytest
from django.db import IntegrityError, connection, models
from django.db.migrations import AddIndex, CreateModel
from psqlextra.indexes import CaseInsensitiveUniqueIndex
from psqlextra.models import PostgresModel
from .fake_model import get_fake_model
from .migrations import apply_migration, filtered_schema_editor

    with filtered_schema_editor("CREATE UNIQUE INDEX") as calls:
        apply_migration(ops)

    sql = str([call[0] for _, call, _ in calls["CREATE UNIQUE INDEX"]][0])
    expected_sql = 'CREATE UNIQUE INDEX "index1" ON "tests_mymodel" (LOWER("name"), LOWER("other_name"))'
    assert sql == expected_sql


def test_ciui():
    """Tests whether the case insensitive unique index works as expected."""

    index_1 = CaseInsensitiveUniqueIndex(fields=["name"], name="index1")

    model = get_fake_model(
        {"name": models.CharField(max_length=255)}, PostgresModel
    )

    with connection.schema_editor() as schema_editor:
        schema_editor.add_index(model, index_1)

    model.objects.create(name="henk")

    with pytest.raises(IntegrityError):
        model.objects.create(name="Henk")


def test_ciui_on_conflict():
    """Tests wether fields with a :see:CaseInsensitiveUniqueIndex can be used
    as a conflict target."""


    index_1 = CaseInsensitiveUniqueIndex(fields=["name"], name="index1")