introspection.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. from collections import namedtuple
  2. from MySQLdb.constants import FIELD_TYPE
  3. from django.db.backends.base.introspection import (
  4. BaseDatabaseIntrospection, FieldInfo, TableInfo,
  5. )
  6. from django.utils.datastructures import OrderedSet
  7. from django.utils.encoding import force_text
  8. FieldInfo = namedtuple('FieldInfo', FieldInfo._fields + ('extra',))
  9. class DatabaseIntrospection(BaseDatabaseIntrospection):
  10. data_types_reverse = {
  11. FIELD_TYPE.BLOB: 'TextField',
  12. FIELD_TYPE.CHAR: 'CharField',
  13. FIELD_TYPE.DECIMAL: 'DecimalField',
  14. FIELD_TYPE.NEWDECIMAL: 'DecimalField',
  15. FIELD_TYPE.DATE: 'DateField',
  16. FIELD_TYPE.DATETIME: 'DateTimeField',
  17. FIELD_TYPE.DOUBLE: 'FloatField',
  18. FIELD_TYPE.FLOAT: 'FloatField',
  19. FIELD_TYPE.INT24: 'IntegerField',
  20. FIELD_TYPE.LONG: 'IntegerField',
  21. FIELD_TYPE.LONGLONG: 'BigIntegerField',
  22. FIELD_TYPE.SHORT: 'SmallIntegerField',
  23. FIELD_TYPE.STRING: 'CharField',
  24. FIELD_TYPE.TIME: 'TimeField',
  25. FIELD_TYPE.TIMESTAMP: 'DateTimeField',
  26. FIELD_TYPE.TINY: 'IntegerField',
  27. FIELD_TYPE.TINY_BLOB: 'TextField',
  28. FIELD_TYPE.MEDIUM_BLOB: 'TextField',
  29. FIELD_TYPE.LONG_BLOB: 'TextField',
  30. FIELD_TYPE.VAR_STRING: 'CharField',
  31. }
  32. def get_field_type(self, data_type, description):
  33. field_type = super(DatabaseIntrospection, self).get_field_type(data_type, description)
  34. if field_type == 'IntegerField' and 'auto_increment' in description.extra:
  35. return 'AutoField'
  36. return field_type
  37. def get_table_list(self, cursor):
  38. """
  39. Returns a list of table and view names in the current database.
  40. """
  41. cursor.execute("SHOW FULL TABLES")
  42. return [TableInfo(row[0], {'BASE TABLE': 't', 'VIEW': 'v'}.get(row[1]))
  43. for row in cursor.fetchall()]
  44. def get_table_description(self, cursor, table_name):
  45. """
  46. Returns a description of the table, with the DB-API cursor.description interface."
  47. """
  48. # information_schema database gives more accurate results for some figures:
  49. # - varchar length returned by cursor.description is an internal length,
  50. # not visible length (#5725)
  51. # - precision and scale (for decimal fields) (#5014)
  52. # - auto_increment is not available in cursor.description
  53. InfoLine = namedtuple('InfoLine', 'col_name data_type max_len num_prec num_scale extra')
  54. cursor.execute("""
  55. SELECT column_name, data_type, character_maximum_length, numeric_precision, numeric_scale, extra
  56. FROM information_schema.columns
  57. WHERE table_name = %s AND table_schema = DATABASE()""", [table_name])
  58. field_info = {line[0]: InfoLine(*line) for line in cursor.fetchall()}
  59. cursor.execute("SELECT * FROM %s LIMIT 1" % self.connection.ops.quote_name(table_name))
  60. to_int = lambda i: int(i) if i is not None else i
  61. fields = []
  62. for line in cursor.description:
  63. col_name = force_text(line[0])
  64. fields.append(
  65. FieldInfo(*((col_name,)
  66. + line[1:3]
  67. + (to_int(field_info[col_name].max_len) or line[3],
  68. to_int(field_info[col_name].num_prec) or line[4],
  69. to_int(field_info[col_name].num_scale) or line[5])
  70. + (line[6],)
  71. + (field_info[col_name].extra,)))
  72. )
  73. return fields
  74. def get_relations(self, cursor, table_name):
  75. """
  76. Returns a dictionary of {field_name: (field_name_other_table, other_table)}
  77. representing all relationships to the given table.
  78. """
  79. constraints = self.get_key_columns(cursor, table_name)
  80. relations = {}
  81. for my_fieldname, other_table, other_field in constraints:
  82. relations[my_fieldname] = (other_field, other_table)
  83. return relations
  84. def get_key_columns(self, cursor, table_name):
  85. """
  86. Returns a list of (column_name, referenced_table_name, referenced_column_name) for all
  87. key columns in given table.
  88. """
  89. key_columns = []
  90. cursor.execute("""
  91. SELECT column_name, referenced_table_name, referenced_column_name
  92. FROM information_schema.key_column_usage
  93. WHERE table_name = %s
  94. AND table_schema = DATABASE()
  95. AND referenced_table_name IS NOT NULL
  96. AND referenced_column_name IS NOT NULL""", [table_name])
  97. key_columns.extend(cursor.fetchall())
  98. return key_columns
  99. def get_indexes(self, cursor, table_name):
  100. cursor.execute("SHOW INDEX FROM %s" % self.connection.ops.quote_name(table_name))
  101. # Do a two-pass search for indexes: on first pass check which indexes
  102. # are multicolumn, on second pass check which single-column indexes
  103. # are present.
  104. rows = list(cursor.fetchall())
  105. multicol_indexes = set()
  106. for row in rows:
  107. if row[3] > 1:
  108. multicol_indexes.add(row[2])
  109. indexes = {}
  110. for row in rows:
  111. if row[2] in multicol_indexes:
  112. continue
  113. if row[4] not in indexes:
  114. indexes[row[4]] = {'primary_key': False, 'unique': False}
  115. # It's possible to have the unique and PK constraints in separate indexes.
  116. if row[2] == 'PRIMARY':
  117. indexes[row[4]]['primary_key'] = True
  118. if not row[1]:
  119. indexes[row[4]]['unique'] = True
  120. return indexes
  121. def get_storage_engine(self, cursor, table_name):
  122. """
  123. Retrieves the storage engine for a given table. Returns the default
  124. storage engine if the table doesn't exist.
  125. """
  126. cursor.execute(
  127. "SELECT engine "
  128. "FROM information_schema.tables "
  129. "WHERE table_name = %s", [table_name])
  130. result = cursor.fetchone()
  131. if not result:
  132. return self.connection.features._mysql_storage_engine
  133. return result[0]
  134. def get_constraints(self, cursor, table_name):
  135. """
  136. Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.
  137. """
  138. constraints = {}
  139. # Get the actual constraint names and columns
  140. name_query = """
  141. SELECT kc.`constraint_name`, kc.`column_name`,
  142. kc.`referenced_table_name`, kc.`referenced_column_name`
  143. FROM information_schema.key_column_usage AS kc
  144. WHERE
  145. kc.table_schema = %s AND
  146. kc.table_name = %s
  147. """
  148. cursor.execute(name_query, [self.connection.settings_dict['NAME'], table_name])
  149. for constraint, column, ref_table, ref_column in cursor.fetchall():
  150. if constraint not in constraints:
  151. constraints[constraint] = {
  152. 'columns': OrderedSet(),
  153. 'primary_key': False,
  154. 'unique': False,
  155. 'index': False,
  156. 'check': False,
  157. 'foreign_key': (ref_table, ref_column) if ref_column else None,
  158. }
  159. constraints[constraint]['columns'].add(column)
  160. # Now get the constraint types
  161. type_query = """
  162. SELECT c.constraint_name, c.constraint_type
  163. FROM information_schema.table_constraints AS c
  164. WHERE
  165. c.table_schema = %s AND
  166. c.table_name = %s
  167. """
  168. cursor.execute(type_query, [self.connection.settings_dict['NAME'], table_name])
  169. for constraint, kind in cursor.fetchall():
  170. if kind.lower() == "primary key":
  171. constraints[constraint]['primary_key'] = True
  172. constraints[constraint]['unique'] = True
  173. elif kind.lower() == "unique":
  174. constraints[constraint]['unique'] = True
  175. # Now add in the indexes
  176. cursor.execute("SHOW INDEX FROM %s" % self.connection.ops.quote_name(table_name))
  177. for table, non_unique, index, colseq, column in [x[:5] for x in cursor.fetchall()]:
  178. if index not in constraints:
  179. constraints[index] = {
  180. 'columns': OrderedSet(),
  181. 'primary_key': False,
  182. 'unique': False,
  183. 'index': True,
  184. 'check': False,
  185. 'foreign_key': None,
  186. }
  187. constraints[index]['index'] = True
  188. constraints[index]['columns'].add(column)
  189. # Convert the sorted sets to lists
  190. for constraint in constraints.values():
  191. constraint['columns'] = list(constraint['columns'])
  192. return constraints