You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

209 lines
8.8 KiB

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