Ticket #1483: add-mysql-fkey-inspection.diff
File add-mysql-fkey-inspection.diff, 2.4 KB (added by , 19 years ago) |
---|
-
django/db/backends/mysql/introspection.py
1 1 from django.db import transaction 2 2 from django.db.backends.mysql.base import quote_name 3 3 from MySQLdb.constants import FIELD_TYPE 4 import re 4 5 6 # parses a foreign key constraint from show create table 7 # fieldname other_field other_table 8 fkey_parser = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)") 9 5 10 def get_table_list(cursor): 6 11 "Returns a list of table names in the current database." 7 12 cursor.execute("SHOW TABLES") … … 12 17 cursor.execute("SELECT * FROM %s LIMIT 1" % quote_name(table_name)) 13 18 return cursor.description 14 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 15 33 def get_relations(cursor, table_name): 16 raise NotImplementedError 34 """ 35 Returns a dictionary of {field_index: (field_index_other_table, other_table)} 36 representing all relationships to the given table. Indexes are 0-based. 37 """ 38 my_field_dict = _name_to_index(cursor, table_name) 39 constraints = [ ] 40 relations = {} 41 42 # go through all constraints (== matches) and save these 43 cursor.execute("SHOW CREATE TABLE "+ table_name) 44 for row in cursor.fetchall(): 45 pos = 0 46 while True: 47 match = fkey_parser.search(row[1], pos) 48 if match == None: 49 break 50 pos = match.end() 51 constraints.append(match.groups()) 52 53 # handle constraints. (can't do this in the loop above since we need the cursor here) 54 for (my_fieldname, other_table, other_field) in constraints: 55 other_field_index = _name_to_index(cursor, other_table)[other_field] 56 my_field_index = my_field_dict[my_fieldname] 57 relations[my_field_index] = (other_field_index, other_table) 58 return relations 17 59 18 60 def get_indexes(cursor, table_name): 19 61 """