Skip to content

Commit 879b245

Browse files
committed
Fixed django#5725 -- Fixed varchar column size introspection for MySQL
Thanks ferdonline for the initial patch and Karen Tracey for the related post on django-users.
1 parent fb3d916 commit 879b245

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

django/db/backends/mysql/introspection.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,20 @@ def get_table_list(self, cursor):
3636
return [row[0] for row in cursor.fetchall()]
3737

3838
def get_table_description(self, cursor, table_name):
39-
"Returns a description of the table, with the DB-API cursor.description interface."
39+
"""
40+
Returns a description of the table, with the DB-API cursor.description interface."
41+
"""
42+
# varchar length returned by cursor.description is an internal length,
43+
# not visible length (#5725), use information_schema database to fix this
44+
cursor.execute("""
45+
SELECT column_name, character_maximum_length FROM information_schema.columns
46+
WHERE table_name = %s AND table_schema = DATABASE()
47+
AND character_maximum_length IS NOT NULL""", [table_name])
48+
length_map = dict(cursor.fetchall())
49+
4050
cursor.execute("SELECT * FROM %s LIMIT 1" % self.connection.ops.quote_name(table_name))
41-
return cursor.description
51+
return [line[:3] + (length_map.get(line[0], line[3]),) + line[4:]
52+
for line in cursor.description]
4253

4354
def _name_to_index(self, cursor, table_name):
4455
"""

tests/regressiontests/introspection/tests.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,11 @@ def test_get_table_description_types(self):
8989
[datatype(r[1], r) for r in desc],
9090
['IntegerField', 'CharField', 'CharField', 'CharField', 'BigIntegerField']
9191
)
92+
# Check also length of CharFields
93+
self.assertEqual(
94+
[r[3] for r in desc if datatype(r[1], r) == 'CharField'],
95+
[30, 30, 75]
96+
)
9297

9398
# Oracle forces null=True under the hood in some cases (see
9499
# https://docs.djangoproject.com/en/dev/ref/databases/#null-and-empty-strings)

0 commit comments

Comments
 (0)