Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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
Adrian Holovaty authored April 13, 2006
1  AUTHORS
@@ -80,6 +80,7 @@ answer newbie questions, and generally made Django that much better:
80 80
     mattycakes@gmail.com
81 81
     Jason McBrayer <http://www.carcosa.net/jason/>
82 82
     michael.mcewan@gmail.com
  83
+    mir@noris.de
83 84
     mmarshall
84 85
     Eric Moritz <http://eric.themoritzfamily.com/>
85 86
     Robin Munn <http://www.geekforgod.com/>
47  django/db/backends/mysql/introspection.py
... ...
@@ -1,6 +1,10 @@
1 1
 from django.db import transaction
2 2
 from django.db.backends.mysql.base import quote_name
  3
+from MySQLdb import ProgrammingError, OperationalError
3 4
 from MySQLdb.constants import FIELD_TYPE
  5
+import re
  6
+
  7
+foreign_key_re = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)")
4 8
 
5 9
 def get_table_list(cursor):
6 10
     "Returns a list of table names in the current database."
@@ -12,8 +16,49 @@ def get_table_description(cursor, table_name):
12 16
     cursor.execute("SELECT * FROM %s LIMIT 1" % quote_name(table_name))
13 17
     return cursor.description
14 18
 
  19
+def _name_to_index(cursor, table_name):
  20
+    """
  21
+    Returns a dictionary of {field_name: field_index} for the given table.
  22
+    Indexes are 0-based.
  23
+    """
  24
+    return dict([(d[0], i) for i, d in enumerate(get_table_description(cursor, table_name))])
  25
+
15 26
 def get_relations(cursor, table_name):
16  
-    raise NotImplementedError
  27
+    """
  28
+    Returns a dictionary of {field_index: (field_index_other_table, other_table)}
  29
+    representing all relationships to the given table. Indexes are 0-based.
  30
+    """
  31
+    my_field_dict = _name_to_index(cursor, table_name)
  32
+    constraints = []
  33
+    relations = {}
  34
+    try:
  35
+        # This should work for MySQL 5.0.
  36
+        cursor.execute("""
  37
+            SELECT column_name, referenced_table_name, referenced_column_name
  38
+            FROM information_schema.key_column_usage
  39
+            WHERE table_name = %s
  40
+                AND referenced_table_name IS NOT NULL
  41
+                AND referenced_column_name IS NOT NULL""", [table_name])
  42
+        constraints.extend(cursor.fetchall())
  43
+    except (ProgrammingError, OperationalError):
  44
+        # Fall back to "SHOW CREATE TABLE", for previous MySQL versions.
  45
+        # Go through all constraints and save the equal matches.
  46
+        cursor.execute("SHOW CREATE TABLE %s" % table_name)
  47
+        for row in cursor.fetchall():
  48
+            pos = 0
  49
+            while True:
  50
+                match = foreign_key_re.search(row[1], pos)
  51
+                if match == None:
  52
+                    break
  53
+                pos = match.end()
  54
+                constraints.append(match.groups())
  55
+
  56
+    for my_fieldname, other_table, other_field in constraints:
  57
+        other_field_index = _name_to_index(cursor, other_table)[other_field]
  58
+        my_field_index = my_field_dict[my_fieldname]
  59
+        relations[my_field_index] = (other_field_index, other_table)
  60
+
  61
+    return relations
17 62
 
18 63
 def get_indexes(cursor, table_name):
19 64
     """

0 notes on commit 93d95b3

Please sign in to comment.
Something went wrong with that request. Please try again.