Code

Ticket #2495: 2495-against-10914.diff

File 2495-against-10914.diff, 2.4 KB (added by Honza_Kral, 5 years ago)

Added tests and cleaned up the patch a bit

Line 
1commit 3f01282db09f1e618748ed2a8b629eff8529e7a4
2Author: Honza Kral <honza.kral@gmail.com>
3Date:   Fri Jun 5 23:17:15 2009 +0200
4
5    Added tests and patch for #2495
6
7diff --git a/django/db/backends/mysql/creation.py b/django/db/backends/mysql/creation.py
8index 0611e01..a1e3cf4 100644
9--- a/django/db/backends/mysql/creation.py
10+++ b/django/db/backends/mysql/creation.py
11@@ -63,4 +63,32 @@ class DatabaseCreation(BaseDatabaseCreation):
12                 field.rel.to._meta.db_table, field.rel.to._meta.pk.column)
13             ]
14         return table_output, deferred
15-       
16\ No newline at end of file
17+
18+    def sql_indexes_for_field(self, model, f, style):
19+        """
20+        Modify the return-value of BaseDatabaseCreation.sql_indexes_for_field()
21+        to add a  prefix length to the TextField which is currently represented
22+        by MySQL's 'longtext' type -- which requires a prefix-length parameter
23+        in order to install an index.
24+
25+        Use largest possible value allowed - 255 characters.
26+
27+        All other types are passed unchanged.
28+        """
29+
30+        out = super(DatabaseCreation, self).sql_indexes_for_field(model, f, style)
31+
32+        if not out or not f.db_type() == self.data_types['TextField']:
33+            return out
34+
35+        qn = self.connection.ops.quote_name
36+        field = "%s" % style.SQL_FIELD(qn(f.column))
37+
38+        newout = []
39+        for item in out:
40+            # 767-byte prefix length maximum for InnoDB
41+            # when using UTF-8 count 3 bytes per character so use 255 as a safe value
42+            newout.append(item.replace(field, "%s(255)" % field))
43+
44+        return newout
45+
46diff --git a/tests/regressiontests/bug2495/__init__.py b/tests/regressiontests/bug2495/__init__.py
47new file mode 100644
48index 0000000..e69de29
49diff --git a/tests/regressiontests/bug2495/models.py b/tests/regressiontests/bug2495/models.py
50new file mode 100644
51index 0000000..91661b3
52--- /dev/null
53+++ b/tests/regressiontests/bug2495/models.py
54@@ -0,0 +1,15 @@
55+from unittest import TestCase
56+
57+from django.db import models, connection
58+
59+class IndexedTextModel(models.Model):
60+    indexed_text = models.TextField(db_index=True)
61+
62+class TestTextFieldIndices(TestCase):
63+    def test_indexed_text_has_an_index(self):
64+        try:
65+            indexes = connection.introspection.get_indexes(connection.cursor(), IndexedTextModel._meta.db_table)
66+        except NotImplementedError:
67+            indexes = {}
68+        assert 'indexed_text' in indexes
69+