From f28d29e8b726b8b013e8739fab542a796f348e78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Saulius=20=C5=BDemaitaitis?= Date: Sat, 5 Nov 2016 13:46:59 +0100 Subject: [PATCH] Fixed #27372 -- Fixed introspection of SQLite foreign keys with spaces in DDL. Thanks samuller for the report and initial patch. --- django/db/backends/sqlite3/introspection.py | 2 +- tests/introspection/tests.py | 24 +++++++++++---------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/django/db/backends/sqlite3/introspection.py b/django/db/backends/sqlite3/introspection.py index ce5e7032fb..d68b5e7d12 100644 --- a/django/db/backends/sqlite3/introspection.py +++ b/django/db/backends/sqlite3/introspection.py @@ -132,7 +132,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): if field_desc.startswith("FOREIGN KEY"): # Find name of the target FK field - m = re.match(r'FOREIGN KEY\(([^\)]*)\).*', field_desc, re.I) + m = re.match(r'FOREIGN KEY\s*\(([^\)]*)\).*', field_desc, re.I) field_name = m.groups()[0].strip('"') else: field_name = field_desc.split()[0].strip('"') diff --git a/tests/introspection/tests.py b/tests/introspection/tests.py index 7c60902deb..7bee998043 100644 --- a/tests/introspection/tests.py +++ b/tests/introspection/tests.py @@ -143,17 +143,19 @@ class IntrospectionTests(TransactionTestCase): @skipUnless(connection.vendor == 'sqlite', "This is an sqlite-specific issue") def test_get_relations_alt_format(self): - """With SQLite, foreign keys can be added with different syntaxes.""" - with connection.cursor() as cursor: - cursor.fetchone = mock.Mock( - return_value=[ - "CREATE TABLE track(id, art_id INTEGER, FOREIGN KEY(art_id) REFERENCES {}(id));".format( - Article._meta.db_table - ) - ] - ) - relations = connection.introspection.get_relations(cursor, 'mocked_table') - self.assertEqual(relations, {'art_id': ('id', Article._meta.db_table)}) + """ + With SQLite, foreign keys can be added with different syntaxes and + formatting. + """ + create_table_statements = [ + "CREATE TABLE track(id, art_id INTEGER, FOREIGN KEY(art_id) REFERENCES {}(id));", + "CREATE TABLE track(id, art_id INTEGER, FOREIGN KEY (art_id) REFERENCES {}(id));" + ] + for statement in create_table_statements: + with connection.cursor() as cursor: + cursor.fetchone = mock.Mock(return_value=[statement.format(Article._meta.db_table)]) + relations = connection.introspection.get_relations(cursor, 'mocked_table') + self.assertEqual(relations, {'art_id': ('id', Article._meta.db_table)}) @skipUnlessDBFeature('can_introspect_foreign_keys') def test_get_key_columns(self):