Code

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

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

patch

Line 
1Index: django/db/backends/mysql/introspection.py
2===================================================================
3--- django/db/backends/mysql/introspection.py   (Revision 2501)
4+++ django/db/backends/mysql/introspection.py   (Arbeitskopie)
5@@ -1,7 +1,12 @@
6 from django.db import transaction
7 from django.db.backends.mysql.base import quote_name
8 from MySQLdb.constants import FIELD_TYPE
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     cursor.execute("SHOW TABLES")
18@@ -12,8 +17,45 @@
19     cursor.execute("SELECT * FROM %s LIMIT 1" % quote_name(table_name))
20     return cursor.description
21 
22+def _name_to_index(cursor, table_name):
23+    """
24+    Returns a dictionary of { field_name: field_index } for the given table.
25+    Indexes are 0-based.
26+    """
27+    descr = get_table_description(cursor, table_name)
28+    res = { }
29+    i=0
30+    for (name, type_code, display_size, internal_size, precision, scale, null_ok) in descr:
31+        res[name] = i
32+        i += 1
33+    return res
34+
35 def get_relations(cursor, table_name):
36-    raise NotImplementedError
37+    """
38+    Returns a dictionary of {field_index: (field_index_other_table, other_table)}
39+    representing all relationships to the given table. Indexes are 0-based.
40+    """
41+    my_field_dict = _name_to_index(cursor, table_name)
42+    constraints = [ ]
43+    relations = {}
44+   
45+    # go through all constraints (== matches) and save these
46+    cursor.execute("SHOW CREATE TABLE "+ table_name)
47+    for row in cursor.fetchall():
48+        pos = 0
49+        while True:
50+            match = fkey_parser.search(row[1], pos)
51+            if match == None:
52+                break
53+            pos = match.end()
54+            constraints.append(match.groups())
55+   
56+    # handle constraints. (can't do this in the loop above since we need the cursor here)
57+    for (my_fieldname, other_table, other_field) in constraints:
58+        other_field_index = _name_to_index(cursor, other_table)[other_field]
59+        my_field_index = my_field_dict[my_fieldname]
60+        relations[my_field_index] = (other_field_index, other_table)
61+    return relations
62 
63 def get_indexes(cursor, table_name):
64     """