Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

magic-removal: Fixed #1483 -- Added MySQL foreign-key inspection to '…

…inspectdb'. Thanks, mir@noris.de

git-svn-id: http://code.djangoproject.com/svn/django/branches/magic-removal@2691 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 93d95b3b10b4904e8efec7d58232e61562533262 1 parent 873b12b
@adrianholovaty adrianholovaty authored
Showing with 47 additions and 1 deletion.
  1. +1 −0  AUTHORS
  2. +46 −1 django/db/backends/mysql/introspection.py
View
1  AUTHORS
@@ -80,6 +80,7 @@ answer newbie questions, and generally made Django that much better:
mattycakes@gmail.com
Jason McBrayer <http://www.carcosa.net/jason/>
michael.mcewan@gmail.com
+ mir@noris.de
mmarshall
Eric Moritz <http://eric.themoritzfamily.com/>
Robin Munn <http://www.geekforgod.com/>
View
47 django/db/backends/mysql/introspection.py
@@ -1,6 +1,10 @@
from django.db import transaction
from django.db.backends.mysql.base import quote_name
+from MySQLdb import ProgrammingError, OperationalError
from MySQLdb.constants import FIELD_TYPE
+import re
+
+foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)")
def get_table_list(cursor):
"Returns a list of table names in the current database."
@@ -12,8 +16,49 @@ def get_table_description(cursor, table_name):
cursor.execute("SELECT * FROM %s LIMIT 1" % quote_name(table_name))
return cursor.description
+def _name_to_index(cursor, table_name):
+ """
+ Returns a dictionary of {field_name: field_index} for the given table.
+ Indexes are 0-based.
+ """
+ return dict([(d[0], i) for i, d in enumerate(get_table_description(cursor, table_name))])
+
def get_relations(cursor, table_name):
- raise NotImplementedError
+ """
+ Returns a dictionary of {field_index: (field_index_other_table, other_table)}
+ representing all relationships to the given table. Indexes are 0-based.
+ """
+ my_field_dict = _name_to_index(cursor, table_name)
+ constraints = []
+ relations = {}
+ try:
+ # This should work for MySQL 5.0.
+ cursor.execute("""
+ SELECT column_name, referenced_table_name, referenced_column_name
+ FROM information_schema.key_column_usage
+ WHERE table_name = %s
+ AND referenced_table_name IS NOT NULL
+ AND referenced_column_name IS NOT NULL""", [table_name])
+ constraints.extend(cursor.fetchall())
+ except (ProgrammingError, OperationalError):
+ # Fall back to "SHOW CREATE TABLE", for previous MySQL versions.
+ # Go through all constraints and save the equal matches.
+ cursor.execute("SHOW CREATE TABLE %s" % table_name)
+ for row in cursor.fetchall():
+ pos = 0
+ while True:
+ match = foreign_key_re.search(row[1], pos)
+ if match == None:
+ break
+ pos = match.end()
+ constraints.append(match.groups())
+
+ for my_fieldname, other_table, other_field in constraints:
+ other_field_index = _name_to_index(cursor, other_table)[other_field]
+ my_field_index = my_field_dict[my_fieldname]
+ relations[my_field_index] = (other_field_index, other_table)
+
+ return relations
def get_indexes(cursor, table_name):
"""
Please sign in to comment.
Something went wrong with that request. Please try again.