#9779: Adding Foreign Key detection to SQLite inspectdb
---------------------------------------+------------------------------------
 Reporter:  gabbott                    |       Owner:  nobody    
   Status:  new                        |   Milestone:            
Component:  django-admin.py inspectdb  |     Version:  SVN       
 Keywords:                             |       Stage:  Unreviewed
Has_patch:  1                          |  
---------------------------------------+------------------------------------
 I was using the SQLite introspection and realized that it didn't support
 foreign key detection. I realize that SQLite does not enforce the
 "reference" sqlite commands the data is there and can easily be parsed
 out. Here is my patch:

 {{{
 Index: django/db/backends/sqlite3/introspection.py
 ===================================================================
 --- django/db/backends/sqlite3/introspection.py (revision 9627)
 +++ django/db/backends/sqlite3/introspection.py (working copy)
 @@ -55,8 +55,59 @@
                   info['null_ok']) for info in self._table_info(cursor,
 table_name)]

      def get_relations(self, cursor, table_name):
 -        raise NotImplementedError
 +        """
 +        Returns a dictionary of {field_index: (field_index_other_table,
 other_table)}
 +        representing all relationships to the given table. Indexes are
 0-based.
 +        """
 +
 +        import re
 +
 +        # Dictionary of relations to return
 +        relations = {}
 +
 +        # Schema for this table
 +        cursor.execute("select sql from sqlite_master where
 tbl_name='%s'" % table_name)
 +        results = cursor.fetchone()[0].strip()
 +        results = results.split('(', 1)[1]
 +        results = results.rsplit(')', 1)[0]

 +        # walk through and look for references to other tables.
 +        for index, i in enumerate(results.split(',')):
 +            i = i.strip()
 +            if i.startswith("UNIQUE"):
 +                continue
 +
 +            m = re.search('references (.*) \(["|](.*)["|]\)', i, re.I)
 +
 +            if not m:
 +                continue
 +
 +            table, column = m.groups()
 +
 +            table = table.strip('"')
 +            column = column.strip('"')
 +
 +            cursor.execute("select sql from sqlite_master where
 tbl_name='%s'" % table)
 +
 +            other_table_results = cursor.fetchone()[0].strip()
 +            other_table_results = other_table_results.split('(', 1)[1]
 +            other_table_results = other_table_results.rsplit(')', 1)[0]
 +
 +            second_index = None
 +            for _index, j in enumerate(other_table_results.split(',')):
 +                j = j.strip()
 +                if j.startswith('UNIQUE'):
 +                    continue
 +
 +                name = j.split(' ', 1)[0].strip('"')
 +                if name == column:
 +                    second_index = _index
 +
 +            if second_index != None:
 +                relations[index] = (second_index, table)
 +
 +        return relations
 +
      def get_indexes(self, cursor, table_name):
          """
          Returns a dictionary of fieldname -> infodict for the given
 table,
 }}}

-- 
Ticket URL: <http://code.djangoproject.com/ticket/9779>
Django <http://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-updates?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to