Ticket #9779: 9779-fk-introspection-for-sqlite.diff

File 9779-fk-introspection-for-sqlite.diff, 2.3 KB (added by Ramiro Morales, 15 years ago)

patch by gabbott in .diff form

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

    diff -r 414bff35ef18 django/db/backends/sqlite3/introspection.py
    a b  
    5555                 info['null_ok']) for info in self._table_info(cursor, table_name)]
    5656
    5757    def get_relations(self, cursor, table_name):
    58         raise NotImplementedError
     58        """
     59        Returns a dictionary of {field_index: (field_index_other_table, other_table)}
     60        representing all relationships to the given table. Indexes are 0-based.
     61        """
     62       
     63        import re
     64       
     65        # Dictionary of relations to return
     66        relations = {}
     67       
     68        # Schema for this table
     69        cursor.execute("select sql from sqlite_master where tbl_name='%s'" % table_name)
     70        results = cursor.fetchone()[0].strip()
     71        results = results.split('(', 1)[1]
     72        results = results.rsplit(')', 1)[0]
     73
     74        # walk through and look for references to other tables.
     75        for index, i in enumerate(results.split(',')):
     76            i = i.strip()
     77            if i.startswith("UNIQUE"):
     78                continue
     79
     80            m = re.search('references (.*) \(["|](.*)["|]\)', i, re.I)
     81           
     82            if not m:
     83                continue
     84       
     85            table, column = m.groups()
     86           
     87            table = table.strip('"')
     88            column = column.strip('"')
     89           
     90            cursor.execute("select sql from sqlite_master where tbl_name='%s'" % table)
     91           
     92            other_table_results = cursor.fetchone()[0].strip()
     93            other_table_results = other_table_results.split('(', 1)[1]
     94            other_table_results = other_table_results.rsplit(')', 1)[0]
     95           
     96            second_index = None
     97            for _index, j in enumerate(other_table_results.split(',')):
     98                j = j.strip()
     99                if j.startswith('UNIQUE'):
     100                    continue
     101
     102                name = j.split(' ', 1)[0].strip('"')
     103                if name == column:
     104                    second_index = _index
     105           
     106            if second_index != None:
     107                relations[index] = (second_index, table)
     108                           
     109        return relations
    59110
    60111    def get_indexes(self, cursor, table_name):
    61112        """
Back to Top