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

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

patch

  • django/db/backends/mysql/introspection.py

     
    11from django.db import transaction
    22from django.db.backends.mysql.base import quote_name
    33from MySQLdb.constants import FIELD_TYPE
     4import re
    45
     6# parses a foreign key constraint from show create table
     7#                                                               fieldname              other_field other_table
     8fkey_parser = re.compile(r"\sCONSTRAINT `[^`]*` FOREIGN KEY \(`([^`]*)`\) REFERENCES `([^`]*)` \(`([^`]*)`\)")
     9
    510def get_table_list(cursor):
    611    "Returns a list of table names in the current database."
    712    cursor.execute("SHOW TABLES")
     
    1217    cursor.execute("SELECT * FROM %s LIMIT 1" % quote_name(table_name))
    1318    return cursor.description
    1419
     20def _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
    1533def 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
    1759
    1860def get_indexes(cursor, table_name):
    1961    """
Back to Top