introspection.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. SELECT name, type FROM sqlite_master
  69. WHERE type in ('table', 'view') AND NOT name='sqlite_sequence'
  70. ORDER BY name""")
  71. return [TableInfo(row[0], row[1][0]) for row in cursor.fetchall()]
  72. def get_table_description(self, cursor, table_name):
  73. """
  74. Return a description of the table with the DB-API cursor.description
  75. interface.
  76. """
  77. cursor.execute(
  78. "PRAGMA table_xinfo(%s)" % self.connection.ops.quote_name(table_name)
  79. )
  80. table_info = cursor.fetchall()
  81. if not table_info:
  82. raise DatabaseError(f"Table {table_name} does not exist (empty pragma).")
  83. collations = self._get_column_collations(cursor, table_name)
  84. json_columns = set()
  85. if self.connection.features.can_introspect_json_field:
  86. for line in table_info:
  87. column = line[1]
  88. json_constraint_sql = '%%json_valid("%s")%%' % column
  89. has_json_constraint = cursor.execute(
  90. """
  91. SELECT sql
  92. FROM sqlite_master
  93. WHERE
  94. type = 'table' AND
  95. name = %s AND
  96. sql LIKE %s
  97. """,
  98. [table_name, json_constraint_sql],
  99. ).fetchone()
  100. if has_json_constraint:
  101. json_columns.add(column)
  102. table_description = [
  103. FieldInfo(
  104. name,
  105. data_type,
  106. get_field_size(data_type),
  107. None,
  108. None,
  109. None,
  110. not notnull,
  111. default,
  112. collations.get(name),
  113. bool(pk),
  114. name in json_columns,
  115. )
  116. for cid, name, data_type, notnull, default, pk, hidden in table_info
  117. if hidden
  118. in [
  119. 0, # Normal column.
  120. 2, # Virtual generated column.
  121. 3, # Stored generated column.
  122. ]
  123. ]
  124. # If the primary key is composed of multiple columns they should not
  125. # be individually marked as pk.
  126. primary_key = [
  127. index for index, field_info in enumerate(table_description) if field_info.pk
  128. ]
  129. if len(primary_key) > 1:
  130. for index in primary_key:
  131. table_description[index] = table_description[index]._replace(pk=False)
  132. return table_description
  133. def get_sequences(self, cursor, table_name, table_fields=()):
  134. pk_col = self.get_primary_key_column(cursor, table_name)
  135. return [{"table": table_name, "column": pk_col}]
  136. def get_relations(self, cursor, table_name):
  137. """
  138. Return a dictionary of
  139. {column_name: (ref_column_name, ref_table_name, db_on_delete)}
  140. representing all foreign keys in the given table.
  141. """
  142. cursor.execute(
  143. "PRAGMA foreign_key_list(%s)" % self.connection.ops.quote_name(table_name)
  144. )
  145. return {
  146. column_name: (
  147. ref_column_name,
  148. ref_table_name,
  149. self.on_delete_types.get(on_delete),
  150. )
  151. for (
  152. _,
  153. _,
  154. ref_table_name,
  155. column_name,
  156. ref_column_name,
  157. _,
  158. on_delete,
  159. *_,
  160. ) in cursor.fetchall()
  161. }
  162. def get_primary_key_columns(self, cursor, table_name):
  163. cursor.execute(
  164. "PRAGMA table_info(%s)" % self.connection.ops.quote_name(table_name)
  165. )
  166. return [name for _, name, *_, pk in cursor.fetchall() if pk]
  167. def _parse_column_or_constraint_definition(self, tokens, columns):
  168. token = None
  169. is_constraint_definition = None
  170. field_name = None
  171. constraint_name = None
  172. unique = False
  173. unique_columns = []
  174. check = False
  175. check_columns = []
  176. braces_deep = 0
  177. for token in tokens:
  178. if token.match(sqlparse.tokens.Punctuation, "("):
  179. braces_deep += 1
  180. elif token.match(sqlparse.tokens.Punctuation, ")"):
  181. braces_deep -= 1
  182. if braces_deep < 0:
  183. # End of columns and constraints for table definition.
  184. break
  185. elif braces_deep == 0 and token.match(sqlparse.tokens.Punctuation, ","):
  186. # End of current column or constraint definition.
  187. break
  188. # Detect column or constraint definition by first token.
  189. if is_constraint_definition is None:
  190. is_constraint_definition = token.match(
  191. sqlparse.tokens.Keyword, "CONSTRAINT"
  192. )
  193. if is_constraint_definition:
  194. continue
  195. if is_constraint_definition:
  196. # Detect constraint name by second token.
  197. if constraint_name is None:
  198. if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword):
  199. constraint_name = token.value
  200. elif token.ttype == sqlparse.tokens.Literal.String.Symbol:
  201. constraint_name = token.value[1:-1]
  202. # Start constraint columns parsing after UNIQUE keyword.
  203. if token.match(sqlparse.tokens.Keyword, "UNIQUE"):
  204. unique = True
  205. unique_braces_deep = braces_deep
  206. elif unique:
  207. if unique_braces_deep == braces_deep:
  208. if unique_columns:
  209. # Stop constraint parsing.
  210. unique = False
  211. continue
  212. if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword):
  213. unique_columns.append(token.value)
  214. elif token.ttype == sqlparse.tokens.Literal.String.Symbol:
  215. unique_columns.append(token.value[1:-1])
  216. else:
  217. # Detect field name by first token.
  218. if field_name is None:
  219. if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword):
  220. field_name = token.value
  221. elif token.ttype == sqlparse.tokens.Literal.String.Symbol:
  222. field_name = token.value[1:-1]
  223. if token.match(sqlparse.tokens.Keyword, "UNIQUE"):
  224. unique_columns = [field_name]
  225. # Start constraint columns parsing after CHECK keyword.
  226. if token.match(sqlparse.tokens.Keyword, "CHECK"):
  227. check = True
  228. check_braces_deep = braces_deep
  229. elif check:
  230. if check_braces_deep == braces_deep:
  231. if check_columns:
  232. # Stop constraint parsing.
  233. check = False
  234. continue
  235. if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword):
  236. if token.value in columns:
  237. check_columns.append(token.value)
  238. elif token.ttype == sqlparse.tokens.Literal.String.Symbol:
  239. if token.value[1:-1] in columns:
  240. check_columns.append(token.value[1:-1])
  241. unique_constraint = (
  242. {
  243. "unique": True,
  244. "columns": unique_columns,
  245. "primary_key": False,
  246. "foreign_key": None,
  247. "check": False,
  248. "index": False,
  249. }
  250. if unique_columns
  251. else None
  252. )
  253. check_constraint = (
  254. {
  255. "check": True,
  256. "columns": check_columns,
  257. "primary_key": False,
  258. "unique": False,
  259. "foreign_key": None,
  260. "index": False,
  261. }
  262. if check_columns
  263. else None
  264. )
  265. return constraint_name, unique_constraint, check_constraint, token
  266. def _parse_table_constraints(self, sql, columns):
  267. # Check constraint parsing is based of SQLite syntax diagram.
  268. # https://www.sqlite.org/syntaxdiagrams.html#table-constraint
  269. statement = sqlparse.parse(sql)[0]
  270. constraints = {}
  271. unnamed_constrains_index = 0
  272. tokens = (token for token in statement.flatten() if not token.is_whitespace)
  273. # Go to columns and constraint definition
  274. for token in tokens:
  275. if token.match(sqlparse.tokens.Punctuation, "("):
  276. break
  277. # Parse columns and constraint definition
  278. while True:
  279. (
  280. constraint_name,
  281. unique,
  282. check,
  283. end_token,
  284. ) = self._parse_column_or_constraint_definition(tokens, columns)
  285. if unique:
  286. if constraint_name:
  287. constraints[constraint_name] = unique
  288. else:
  289. unnamed_constrains_index += 1
  290. constraints[
  291. "__unnamed_constraint_%s__" % unnamed_constrains_index
  292. ] = unique
  293. if check:
  294. if constraint_name:
  295. constraints[constraint_name] = check
  296. else:
  297. unnamed_constrains_index += 1
  298. constraints[
  299. "__unnamed_constraint_%s__" % unnamed_constrains_index
  300. ] = check
  301. if end_token.match(sqlparse.tokens.Punctuation, ")"):
  302. break
  303. return constraints
  304. def get_constraints(self, cursor, table_name):
  305. """
  306. Retrieve any constraints or keys (unique, pk, fk, check, index) across
  307. one or more columns.
  308. """
  309. constraints = {}
  310. # Find inline check constraints.
  311. try:
  312. table_schema = cursor.execute(
  313. "SELECT sql FROM sqlite_master WHERE type='table' and name=%s",
  314. [table_name],
  315. ).fetchone()[0]
  316. except TypeError:
  317. # table_name is a view.
  318. pass
  319. else:
  320. columns = {
  321. info.name for info in self.get_table_description(cursor, table_name)
  322. }
  323. constraints.update(self._parse_table_constraints(table_schema, columns))
  324. # Get the index info
  325. cursor.execute(
  326. "PRAGMA index_list(%s)" % self.connection.ops.quote_name(table_name)
  327. )
  328. for row in cursor.fetchall():
  329. # Discard last 2 columns.
  330. number, index, unique = row[:3]
  331. cursor.execute(
  332. "SELECT sql FROM sqlite_master WHERE type='index' AND name=%s",
  333. [index],
  334. )
  335. # There's at most one row.
  336. (sql,) = cursor.fetchone() or (None,)
  337. # Inline constraints are already detected in
  338. # _parse_table_constraints(). The reasons to avoid fetching inline
  339. # constraints from `PRAGMA index_list` are:
  340. # - Inline constraints can have a different name and information
  341. # than what `PRAGMA index_list` gives.
  342. # - Not all inline constraints may appear in `PRAGMA index_list`.
  343. if not sql:
  344. # An inline constraint
  345. continue
  346. # Get the index info for that index
  347. cursor.execute(
  348. "PRAGMA index_info(%s)" % self.connection.ops.quote_name(index)
  349. )
  350. for index_rank, column_rank, column in cursor.fetchall():
  351. if index not in constraints:
  352. constraints[index] = {
  353. "columns": [],
  354. "primary_key": False,
  355. "unique": bool(unique),
  356. "foreign_key": None,
  357. "check": False,
  358. "index": True,
  359. }
  360. constraints[index]["columns"].append(column)
  361. # Add type and column orders for indexes
  362. if constraints[index]["index"]:
  363. # SQLite doesn't support any index type other than b-tree
  364. constraints[index]["type"] = Index.suffix
  365. orders = self._get_index_columns_orders(sql)
  366. if orders is not None:
  367. constraints[index]["orders"] = orders
  368. # Get the PK
  369. pk_columns = self.get_primary_key_columns(cursor, table_name)
  370. if pk_columns:
  371. # SQLite doesn't actually give a name to the PK constraint,
  372. # so we invent one. This is fine, as the SQLite backend never
  373. # deletes PK constraints by name, as you can't delete constraints
  374. # in SQLite; we remake the table with a new PK instead.
  375. constraints["__primary__"] = {
  376. "columns": pk_columns,
  377. "primary_key": True,
  378. "unique": False, # It's not actually a unique constraint.
  379. "foreign_key": None,
  380. "check": False,
  381. "index": False,
  382. }
  383. relations = enumerate(self.get_relations(cursor, table_name).items())
  384. constraints.update(
  385. {
  386. f"fk_{index}": {
  387. "columns": [column_name],
  388. "primary_key": False,
  389. "unique": False,
  390. "foreign_key": (ref_table_name, ref_column_name),
  391. "check": False,
  392. "index": False,
  393. }
  394. for index, (
  395. column_name,
  396. (ref_column_name, ref_table_name, _),
  397. ) in relations
  398. }
  399. )
  400. return constraints
  401. def _get_index_columns_orders(self, sql):
  402. tokens = sqlparse.parse(sql)[0]
  403. for token in tokens:
  404. if isinstance(token, sqlparse.sql.Parenthesis):
  405. columns = str(token).strip("()").split(", ")
  406. return ["DESC" if info.endswith("DESC") else "ASC" for info in columns]
  407. return None
  408. def _get_column_collations(self, cursor, table_name):
  409. row = cursor.execute(
  410. """
  411. SELECT sql
  412. FROM sqlite_master
  413. WHERE type = 'table' AND name = %s
  414. """,
  415. [table_name],
  416. ).fetchone()
  417. if not row:
  418. return {}
  419. sql = row[0]
  420. columns = str(sqlparse.parse(sql)[0][-1]).strip("()").split(", ")
  421. collations = {}
  422. for column in columns:
  423. tokens = column[1:].split()
  424. column_name = tokens[0].strip('"')
  425. for index, token in enumerate(tokens):
  426. if token == "COLLATE":
  427. collation = tokens[index + 1]
  428. break
  429. else:
  430. collation = None
  431. collations[column_name] = collation
  432. return collations