introspection.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. from collections import namedtuple
  2. import sqlparse
  3. from django.db import DatabaseError
  4. from django.db.backends.base.introspection import BaseDatabaseIntrospection
  5. from django.db.backends.base.introspection import FieldInfo as BaseFieldInfo
  6. from django.db.backends.base.introspection import TableInfo
  7. from django.db.models import Index
  8. from django.utils.regex_helper import _lazy_re_compile
  9. FieldInfo = namedtuple(
  10. "FieldInfo", BaseFieldInfo._fields + ("pk", "has_json_constraint")
  11. )
  12. field_size_re = _lazy_re_compile(r"^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$")
  13. def get_field_size(name):
  14. """Extract the size number from a "varchar(11)" type name"""
  15. m = field_size_re.search(name)
  16. return int(m[1]) if m else None
  17. # This light wrapper "fakes" a dictionary interface, because some SQLite data
  18. # types include variables in them -- e.g. "varchar(30)" -- and can't be matched
  19. # as a simple dictionary lookup.
  20. class FlexibleFieldLookupDict:
  21. # Maps SQL types to Django Field types. Some of the SQL types have multiple
  22. # entries here because SQLite allows for anything and doesn't normalize the
  23. # field type; it uses whatever was given.
  24. base_data_types_reverse = {
  25. "bool": "BooleanField",
  26. "boolean": "BooleanField",
  27. "smallint": "SmallIntegerField",
  28. "smallint unsigned": "PositiveSmallIntegerField",
  29. "smallinteger": "SmallIntegerField",
  30. "int": "IntegerField",
  31. "integer": "IntegerField",
  32. "bigint": "BigIntegerField",
  33. "integer unsigned": "PositiveIntegerField",
  34. "bigint unsigned": "PositiveBigIntegerField",
  35. "decimal": "DecimalField",
  36. "real": "FloatField",
  37. "text": "TextField",
  38. "char": "CharField",
  39. "varchar": "CharField",
  40. "blob": "BinaryField",
  41. "date": "DateField",
  42. "datetime": "DateTimeField",
  43. "time": "TimeField",
  44. }
  45. def __getitem__(self, key):
  46. key = key.lower().split("(", 1)[0].strip()
  47. return self.base_data_types_reverse[key]
  48. class DatabaseIntrospection(BaseDatabaseIntrospection):
  49. data_types_reverse = FlexibleFieldLookupDict()
  50. def get_field_type(self, data_type, description):
  51. field_type = super().get_field_type(data_type, description)
  52. if description.pk and field_type in {
  53. "BigIntegerField",
  54. "IntegerField",
  55. "SmallIntegerField",
  56. }:
  57. # No support for BigAutoField or SmallAutoField as SQLite treats
  58. # all integer primary keys as signed 64-bit integers.
  59. return "AutoField"
  60. if description.has_json_constraint:
  61. return "JSONField"
  62. return field_type
  63. def get_table_list(self, cursor):
  64. """Return a list of table and view names in the current database."""
  65. # Skip the sqlite_sequence system table used for autoincrement key
  66. # generation.
  67. cursor.execute(
  68. """
  69. SELECT name, type FROM sqlite_master
  70. WHERE type in ('table', 'view') AND NOT name='sqlite_sequence'
  71. ORDER BY name"""
  72. )
  73. return [TableInfo(row[0], row[1][0]) for row in cursor.fetchall()]
  74. def get_table_description(self, cursor, table_name):
  75. """
  76. Return a description of the table with the DB-API cursor.description
  77. interface.
  78. """
  79. cursor.execute(
  80. "PRAGMA table_info(%s)" % self.connection.ops.quote_name(table_name)
  81. )
  82. table_info = cursor.fetchall()
  83. if not table_info:
  84. raise DatabaseError(f"Table {table_name} does not exist (empty pragma).")
  85. collations = self._get_column_collations(cursor, table_name)
  86. json_columns = set()
  87. if self.connection.features.can_introspect_json_field:
  88. for line in table_info:
  89. column = line[1]
  90. json_constraint_sql = '%%json_valid("%s")%%' % column
  91. has_json_constraint = cursor.execute(
  92. """
  93. SELECT sql
  94. FROM sqlite_master
  95. WHERE
  96. type = 'table' AND
  97. name = %s AND
  98. sql LIKE %s
  99. """,
  100. [table_name, json_constraint_sql],
  101. ).fetchone()
  102. if has_json_constraint:
  103. json_columns.add(column)
  104. return [
  105. FieldInfo(
  106. name,
  107. data_type,
  108. get_field_size(data_type),
  109. None,
  110. None,
  111. None,
  112. not notnull,
  113. default,
  114. collations.get(name),
  115. pk == 1,
  116. name in json_columns,
  117. )
  118. for cid, name, data_type, notnull, default, pk in table_info
  119. ]
  120. def get_sequences(self, cursor, table_name, table_fields=()):
  121. pk_col = self.get_primary_key_column(cursor, table_name)
  122. return [{"table": table_name, "column": pk_col}]
  123. def get_relations(self, cursor, table_name):
  124. """
  125. Return a dictionary of {column_name: (ref_column_name, ref_table_name)}
  126. representing all foreign keys in the given table.
  127. """
  128. cursor.execute(
  129. "PRAGMA foreign_key_list(%s)" % self.connection.ops.quote_name(table_name)
  130. )
  131. return {
  132. column_name: (ref_column_name, ref_table_name)
  133. for (
  134. _,
  135. _,
  136. ref_table_name,
  137. column_name,
  138. ref_column_name,
  139. *_,
  140. ) in cursor.fetchall()
  141. }
  142. def get_primary_key_columns(self, cursor, table_name):
  143. cursor.execute(
  144. "PRAGMA table_info(%s)" % self.connection.ops.quote_name(table_name)
  145. )
  146. return [name for _, name, *_, pk in cursor.fetchall() if pk]
  147. def _parse_column_or_constraint_definition(self, tokens, columns):
  148. token = None
  149. is_constraint_definition = None
  150. field_name = None
  151. constraint_name = None
  152. unique = False
  153. unique_columns = []
  154. check = False
  155. check_columns = []
  156. braces_deep = 0
  157. for token in tokens:
  158. if token.match(sqlparse.tokens.Punctuation, "("):
  159. braces_deep += 1
  160. elif token.match(sqlparse.tokens.Punctuation, ")"):
  161. braces_deep -= 1
  162. if braces_deep < 0:
  163. # End of columns and constraints for table definition.
  164. break
  165. elif braces_deep == 0 and token.match(sqlparse.tokens.Punctuation, ","):
  166. # End of current column or constraint definition.
  167. break
  168. # Detect column or constraint definition by first token.
  169. if is_constraint_definition is None:
  170. is_constraint_definition = token.match(
  171. sqlparse.tokens.Keyword, "CONSTRAINT"
  172. )
  173. if is_constraint_definition:
  174. continue
  175. if is_constraint_definition:
  176. # Detect constraint name by second token.
  177. if constraint_name is None:
  178. if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword):
  179. constraint_name = token.value
  180. elif token.ttype == sqlparse.tokens.Literal.String.Symbol:
  181. constraint_name = token.value[1:-1]
  182. # Start constraint columns parsing after UNIQUE keyword.
  183. if token.match(sqlparse.tokens.Keyword, "UNIQUE"):
  184. unique = True
  185. unique_braces_deep = braces_deep
  186. elif unique:
  187. if unique_braces_deep == braces_deep:
  188. if unique_columns:
  189. # Stop constraint parsing.
  190. unique = False
  191. continue
  192. if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword):
  193. unique_columns.append(token.value)
  194. elif token.ttype == sqlparse.tokens.Literal.String.Symbol:
  195. unique_columns.append(token.value[1:-1])
  196. else:
  197. # Detect field name by first token.
  198. if field_name is None:
  199. if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword):
  200. field_name = token.value
  201. elif token.ttype == sqlparse.tokens.Literal.String.Symbol:
  202. field_name = token.value[1:-1]
  203. if token.match(sqlparse.tokens.Keyword, "UNIQUE"):
  204. unique_columns = [field_name]
  205. # Start constraint columns parsing after CHECK keyword.
  206. if token.match(sqlparse.tokens.Keyword, "CHECK"):
  207. check = True
  208. check_braces_deep = braces_deep
  209. elif check:
  210. if check_braces_deep == braces_deep:
  211. if check_columns:
  212. # Stop constraint parsing.
  213. check = False
  214. continue
  215. if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword):
  216. if token.value in columns:
  217. check_columns.append(token.value)
  218. elif token.ttype == sqlparse.tokens.Literal.String.Symbol:
  219. if token.value[1:-1] in columns:
  220. check_columns.append(token.value[1:-1])
  221. unique_constraint = (
  222. {
  223. "unique": True,
  224. "columns": unique_columns,
  225. "primary_key": False,
  226. "foreign_key": None,
  227. "check": False,
  228. "index": False,
  229. }
  230. if unique_columns
  231. else None
  232. )
  233. check_constraint = (
  234. {
  235. "check": True,
  236. "columns": check_columns,
  237. "primary_key": False,
  238. "unique": False,
  239. "foreign_key": None,
  240. "index": False,
  241. }
  242. if check_columns
  243. else None
  244. )
  245. return constraint_name, unique_constraint, check_constraint, token
  246. def _parse_table_constraints(self, sql, columns):
  247. # Check constraint parsing is based of SQLite syntax diagram.
  248. # https://www.sqlite.org/syntaxdiagrams.html#table-constraint
  249. statement = sqlparse.parse(sql)[0]
  250. constraints = {}
  251. unnamed_constrains_index = 0
  252. tokens = (token for token in statement.flatten() if not token.is_whitespace)
  253. # Go to columns and constraint definition
  254. for token in tokens:
  255. if token.match(sqlparse.tokens.Punctuation, "("):
  256. break
  257. # Parse columns and constraint definition
  258. while True:
  259. (
  260. constraint_name,
  261. unique,
  262. check,
  263. end_token,
  264. ) = self._parse_column_or_constraint_definition(tokens, columns)
  265. if unique:
  266. if constraint_name:
  267. constraints[constraint_name] = unique
  268. else:
  269. unnamed_constrains_index += 1
  270. constraints[
  271. "__unnamed_constraint_%s__" % unnamed_constrains_index
  272. ] = unique
  273. if check:
  274. if constraint_name:
  275. constraints[constraint_name] = check
  276. else:
  277. unnamed_constrains_index += 1
  278. constraints[
  279. "__unnamed_constraint_%s__" % unnamed_constrains_index
  280. ] = check
  281. if end_token.match(sqlparse.tokens.Punctuation, ")"):
  282. break
  283. return constraints
  284. def get_constraints(self, cursor, table_name):
  285. """
  286. Retrieve any constraints or keys (unique, pk, fk, check, index) across
  287. one or more columns.
  288. """
  289. constraints = {}
  290. # Find inline check constraints.
  291. try:
  292. table_schema = cursor.execute(
  293. "SELECT sql FROM sqlite_master WHERE type='table' and name=%s"
  294. % (self.connection.ops.quote_name(table_name),)
  295. ).fetchone()[0]
  296. except TypeError:
  297. # table_name is a view.
  298. pass
  299. else:
  300. columns = {
  301. info.name for info in self.get_table_description(cursor, table_name)
  302. }
  303. constraints.update(self._parse_table_constraints(table_schema, columns))
  304. # Get the index info
  305. cursor.execute(
  306. "PRAGMA index_list(%s)" % self.connection.ops.quote_name(table_name)
  307. )
  308. for row in cursor.fetchall():
  309. # SQLite 3.8.9+ has 5 columns, however older versions only give 3
  310. # columns. Discard last 2 columns if there.
  311. number, index, unique = row[:3]
  312. cursor.execute(
  313. "SELECT sql FROM sqlite_master "
  314. "WHERE type='index' AND name=%s" % self.connection.ops.quote_name(index)
  315. )
  316. # There's at most one row.
  317. (sql,) = cursor.fetchone() or (None,)
  318. # Inline constraints are already detected in
  319. # _parse_table_constraints(). The reasons to avoid fetching inline
  320. # constraints from `PRAGMA index_list` are:
  321. # - Inline constraints can have a different name and information
  322. # than what `PRAGMA index_list` gives.
  323. # - Not all inline constraints may appear in `PRAGMA index_list`.
  324. if not sql:
  325. # An inline constraint
  326. continue
  327. # Get the index info for that index
  328. cursor.execute(
  329. "PRAGMA index_info(%s)" % self.connection.ops.quote_name(index)
  330. )
  331. for index_rank, column_rank, column in cursor.fetchall():
  332. if index not in constraints:
  333. constraints[index] = {
  334. "columns": [],
  335. "primary_key": False,
  336. "unique": bool(unique),
  337. "foreign_key": None,
  338. "check": False,
  339. "index": True,
  340. }
  341. constraints[index]["columns"].append(column)
  342. # Add type and column orders for indexes
  343. if constraints[index]["index"]:
  344. # SQLite doesn't support any index type other than b-tree
  345. constraints[index]["type"] = Index.suffix
  346. orders = self._get_index_columns_orders(sql)
  347. if orders is not None:
  348. constraints[index]["orders"] = orders
  349. # Get the PK
  350. pk_columns = self.get_primary_key_columns(cursor, table_name)
  351. if pk_columns:
  352. # SQLite doesn't actually give a name to the PK constraint,
  353. # so we invent one. This is fine, as the SQLite backend never
  354. # deletes PK constraints by name, as you can't delete constraints
  355. # in SQLite; we remake the table with a new PK instead.
  356. constraints["__primary__"] = {
  357. "columns": pk_columns,
  358. "primary_key": True,
  359. "unique": False, # It's not actually a unique constraint.
  360. "foreign_key": None,
  361. "check": False,
  362. "index": False,
  363. }
  364. relations = enumerate(self.get_relations(cursor, table_name).items())
  365. constraints.update(
  366. {
  367. f"fk_{index}": {
  368. "columns": [column_name],
  369. "primary_key": False,
  370. "unique": False,
  371. "foreign_key": (ref_table_name, ref_column_name),
  372. "check": False,
  373. "index": False,
  374. }
  375. for index, (column_name, (ref_column_name, ref_table_name)) in relations
  376. }
  377. )
  378. return constraints
  379. def _get_index_columns_orders(self, sql):
  380. tokens = sqlparse.parse(sql)[0]
  381. for token in tokens:
  382. if isinstance(token, sqlparse.sql.Parenthesis):
  383. columns = str(token).strip("()").split(", ")
  384. return ["DESC" if info.endswith("DESC") else "ASC" for info in columns]
  385. return None
  386. def _get_column_collations(self, cursor, table_name):
  387. row = cursor.execute(
  388. """
  389. SELECT sql
  390. FROM sqlite_master
  391. WHERE type = 'table' AND name = %s
  392. """,
  393. [table_name],
  394. ).fetchone()
  395. if not row:
  396. return {}
  397. sql = row[0]
  398. columns = str(sqlparse.parse(sql)[0][-1]).strip("()").split(", ")
  399. collations = {}
  400. for column in columns:
  401. tokens = column[1:].split()
  402. column_name = tokens[0].strip('"')
  403. for index, token in enumerate(tokens):
  404. if token == "COLLATE":
  405. collation = tokens[index + 1]
  406. break
  407. else:
  408. collation = None
  409. collations[column_name] = collation
  410. return collations