1
0
mirror of https://github.com/django/django.git synced 2025-06-07 12:39:12 +00:00

Refs #30183 -- Moved SQLite table constraint parsing to a method.

This commit is contained in:
Paveł Tyślacki 2019-02-28 00:44:45 +03:00 committed by Tim Graham
parent b777c0675e
commit 4492be348a

View File

@ -217,23 +217,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
} }
return constraints return constraints
def get_constraints(self, cursor, table_name): def _parse_table_constraints(self, sql):
"""
Retrieve any constraints or keys (unique, pk, fk, check, index) across
one or more columns.
"""
constraints = {}
# Find inline check constraints.
try:
table_schema = cursor.execute(
"SELECT sql FROM sqlite_master WHERE type='table' and name=%s" % (
self.connection.ops.quote_name(table_name),
)
).fetchone()[0]
except TypeError:
# table_name is a view.
pass
else:
# Check constraint parsing is based of SQLite syntax diagram. # Check constraint parsing is based of SQLite syntax diagram.
# https://www.sqlite.org/syntaxdiagrams.html#table-constraint # https://www.sqlite.org/syntaxdiagrams.html#table-constraint
def next_ttype(ttype): def next_ttype(ttype):
@ -241,7 +225,8 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
if token.ttype == ttype: if token.ttype == ttype:
return token return token
statement = sqlparse.parse(table_schema)[0] statement = sqlparse.parse(sql)[0]
constraints = {}
tokens = statement.flatten() tokens = statement.flatten()
for token in tokens: for token in tokens:
name = None name = None
@ -276,6 +261,27 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
'foreign_key': None, 'foreign_key': None,
'index': False, 'index': False,
} }
return constraints
def get_constraints(self, cursor, table_name):
"""
Retrieve any constraints or keys (unique, pk, fk, check, index) across
one or more columns.
"""
constraints = {}
# Find inline check constraints.
try:
table_schema = cursor.execute(
"SELECT sql FROM sqlite_master WHERE type='table' and name=%s" % (
self.connection.ops.quote_name(table_name),
)
).fetchone()[0]
except TypeError:
# table_name is a view.
pass
else:
constraints.update(self._parse_table_constraints(table_schema))
# Get the index info # Get the index info
cursor.execute("PRAGMA index_list(%s)" % self.connection.ops.quote_name(table_name)) cursor.execute("PRAGMA index_list(%s)" % self.connection.ops.quote_name(table_name))
for row in cursor.fetchall(): for row in cursor.fetchall():