File: case_insensitive_unique_index.py

package info (click to toggle)
python-django-postgres-extra 2.0.9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,096 kB
  • sloc: python: 9,057; makefile: 17; sh: 7; sql: 1
file content (38 lines) | stat: -rw-r--r-- 1,372 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from django.db.models.indexes import Index


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)