Code

Ticket #1483: add-mysql-fkey-inspection.3.diff

File add-mysql-fkey-inspection.3.diff, 3.0 KB (added by mir@…, 8 years ago)

patch, adds foreign key handling to inspectdb for MySQL. Revised: Includes code for MySQL 5.0 information_schema

Line 
1index fb97bc4..65f255b 100644
2--- a/django/db/backends/mysql/introspection.py
3+++ b/django/db/backends/mysql/introspection.py
4@@ -1,6 +1,12 @@
5 from django.db import transaction
6 from django.db.backends.mysql.base import quote_name
7 from MySQLdb.constants import FIELD_TYPE
8+from MySQLdb import OperationalError
9+import re
10+
11+# parses a foreign key constraint from show create table
12+#                                                               fieldname              other_field other_table
13+FKEY_PARSER = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)")
14 
15 def get_table_list(cursor):
16     "Returns a list of table names in the current database."
17@@ -12,8 +18,58 @@ def get_table_description(cursor, table_
18     cursor.execute("SELECT * FROM %s LIMIT 1" % quote_name(table_name))
19     return cursor.description
20 
21+def _name_to_index(cursor, table_name):
22+    """
23+    Returns a dictionary of { field_name: field_index } for the given table.
24+    Indexes are 0-based.
25+    """
26+    descr = get_table_description(cursor, table_name)
27+    res = { }
28+    i=0
29+    for (name, type_code, display_size, internal_size, precision, scale, null_ok) in descr:
30+        res[name] = i
31+        i += 1
32+    return res
33+
34 def get_relations(cursor, table_name):
35-    raise NotImplementedError
36+    """
37+    Returns a dictionary of {field_index: (field_index_other_table, other_table)}
38+    representing all relationships to the given table. Indexes are 0-based.
39+    """
40+    my_field_dict = _name_to_index(cursor, table_name)
41+    constraints = [ ]
42+    relations = {}
43+   
44+    try:
45+        # This should work for MySQL 5.0
46+        # Shouldn't we limit the select to table_schema?
47+        cursor.execute(
48+            """select column_name, referenced_table_name, referenced_column_name
49+               from information_schema.key_column_usage
50+               where table_name = %s
51+                 and referenced_table_name is not null
52+                 and referenced_column_name is not null""",
53+            [table_name])
54+        constraints.extend(cursor.fetchall())
55+    except OperationalError:
56+        # Fall back to `show create table`
57+        # go through all constraints (== matches) and save these
58+        cursor.execute("SHOW CREATE TABLE "+ table_name)
59+        for row in cursor.fetchall():
60+            pos = 0
61+            while True:
62+                match = FKEY_PARSER.search(row[1], pos)
63+                if match == None:
64+                    break
65+                pos = match.end()
66+                constraints.append(match.groups())
67+
68+    # handle constraints. (can't do this in the loop above since we need the cursor in both places)
69+    for (my_fieldname, other_table, other_field) in constraints:
70+        other_field_index = _name_to_index(cursor, other_table)[other_field]
71+        my_field_index = my_field_dict[my_fieldname]
72+        relations[my_field_index] = (other_field_index, other_table)
73+    return relations
74 
75 def get_indexes(cursor, table_name):
76     """