Code

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

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

trying to find out what doesn't work in my patches :-(

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