2
0

inspectdb.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. from __future__ import unicode_literals
  2. import keyword
  3. import re
  4. from collections import OrderedDict
  5. from django.core.management.base import BaseCommand, CommandError
  6. from django.db import DEFAULT_DB_ALIAS, connections
  7. from django.utils.encoding import force_text
  8. class Command(BaseCommand):
  9. help = "Introspects the database tables in the given database and outputs a Django model module."
  10. requires_system_checks = False
  11. db_module = 'django.db'
  12. def add_arguments(self, parser):
  13. parser.add_argument(
  14. 'table', action='store', nargs='*', type=str,
  15. help='Selects what tables or views should be introspected.',
  16. )
  17. parser.add_argument(
  18. '--database', action='store', dest='database', default=DEFAULT_DB_ALIAS,
  19. help='Nominates a database to introspect. Defaults to using the "default" database.',
  20. )
  21. def handle(self, **options):
  22. try:
  23. for line in self.handle_inspection(options):
  24. self.stdout.write("%s\n" % line)
  25. except NotImplementedError:
  26. raise CommandError("Database inspection isn't supported for the currently selected database backend.")
  27. def handle_inspection(self, options):
  28. connection = connections[options['database']]
  29. # 'table_name_filter' is a stealth option
  30. table_name_filter = options.get('table_name_filter')
  31. def table2model(table_name):
  32. return re.sub(r'[^a-zA-Z0-9]', '', table_name.title())
  33. def strip_prefix(s):
  34. return s[1:] if s.startswith("u'") else s
  35. with connection.cursor() as cursor:
  36. yield "# This is an auto-generated Django model module."
  37. yield "# You'll have to do the following manually to clean this up:"
  38. yield "# * Rearrange models' order"
  39. yield "# * Make sure each model has one field with primary_key=True"
  40. yield "# * Make sure each ForeignKey has `on_delete` set to the desired behavior."
  41. yield (
  42. "# * Remove `managed = False` lines if you wish to allow "
  43. "Django to create, modify, and delete the table"
  44. )
  45. yield "# Feel free to rename the models, but don't rename db_table values or field names."
  46. yield "from __future__ import unicode_literals"
  47. yield ''
  48. yield 'from %s import models' % self.db_module
  49. known_models = []
  50. tables_to_introspect = options['table'] or connection.introspection.table_names(cursor)
  51. for table_name in tables_to_introspect:
  52. if table_name_filter is not None and callable(table_name_filter):
  53. if not table_name_filter(table_name):
  54. continue
  55. try:
  56. try:
  57. relations = connection.introspection.get_relations(cursor, table_name)
  58. except NotImplementedError:
  59. relations = {}
  60. try:
  61. indexes = connection.introspection.get_indexes(cursor, table_name)
  62. except NotImplementedError:
  63. indexes = {}
  64. try:
  65. constraints = connection.introspection.get_constraints(cursor, table_name)
  66. except NotImplementedError:
  67. constraints = {}
  68. table_description = connection.introspection.get_table_description(cursor, table_name)
  69. except Exception as e:
  70. yield "# Unable to inspect table '%s'" % table_name
  71. yield "# The error was: %s" % force_text(e)
  72. continue
  73. yield ''
  74. yield ''
  75. yield 'class %s(models.Model):' % table2model(table_name)
  76. known_models.append(table2model(table_name))
  77. used_column_names = [] # Holds column names used in the table so far
  78. column_to_field_name = {} # Maps column names to names of model fields
  79. for row in table_description:
  80. comment_notes = [] # Holds Field notes, to be displayed in a Python comment.
  81. extra_params = OrderedDict() # Holds Field parameters such as 'db_column'.
  82. column_name = row[0]
  83. is_relation = column_name in relations
  84. att_name, params, notes = self.normalize_col_name(
  85. column_name, used_column_names, is_relation)
  86. extra_params.update(params)
  87. comment_notes.extend(notes)
  88. used_column_names.append(att_name)
  89. column_to_field_name[column_name] = att_name
  90. # Add primary_key and unique, if necessary.
  91. if column_name in indexes:
  92. if indexes[column_name]['primary_key']:
  93. extra_params['primary_key'] = True
  94. elif indexes[column_name]['unique']:
  95. extra_params['unique'] = True
  96. if is_relation:
  97. rel_to = (
  98. "self" if relations[column_name][1] == table_name
  99. else table2model(relations[column_name][1])
  100. )
  101. if rel_to in known_models:
  102. field_type = 'ForeignKey(%s' % rel_to
  103. else:
  104. field_type = "ForeignKey('%s'" % rel_to
  105. else:
  106. # Calling `get_field_type` to get the field type string and any
  107. # additional parameters and notes.
  108. field_type, field_params, field_notes = self.get_field_type(connection, table_name, row)
  109. extra_params.update(field_params)
  110. comment_notes.extend(field_notes)
  111. field_type += '('
  112. # Don't output 'id = meta.AutoField(primary_key=True)', because
  113. # that's assumed if it doesn't exist.
  114. if att_name == 'id' and extra_params == {'primary_key': True}:
  115. if field_type == 'AutoField(':
  116. continue
  117. elif field_type == 'IntegerField(' and not connection.features.can_introspect_autofield:
  118. comment_notes.append('AutoField?')
  119. # Add 'null' and 'blank', if the 'null_ok' flag was present in the
  120. # table description.
  121. if row[6]: # If it's NULL...
  122. if field_type == 'BooleanField(':
  123. field_type = 'NullBooleanField('
  124. else:
  125. extra_params['blank'] = True
  126. extra_params['null'] = True
  127. field_desc = '%s = %s%s' % (
  128. att_name,
  129. # Custom fields will have a dotted path
  130. '' if '.' in field_type else 'models.',
  131. field_type,
  132. )
  133. if field_type.startswith('ForeignKey('):
  134. field_desc += ', models.DO_NOTHING'
  135. if extra_params:
  136. if not field_desc.endswith('('):
  137. field_desc += ', '
  138. field_desc += ', '.join(
  139. '%s=%s' % (k, strip_prefix(repr(v)))
  140. for k, v in extra_params.items())
  141. field_desc += ')'
  142. if comment_notes:
  143. field_desc += ' # ' + ' '.join(comment_notes)
  144. yield ' %s' % field_desc
  145. for meta_line in self.get_meta(table_name, constraints, column_to_field_name):
  146. yield meta_line
  147. def normalize_col_name(self, col_name, used_column_names, is_relation):
  148. """
  149. Modify the column name to make it Python-compatible as a field name
  150. """
  151. field_params = {}
  152. field_notes = []
  153. new_name = col_name.lower()
  154. if new_name != col_name:
  155. field_notes.append('Field name made lowercase.')
  156. if is_relation:
  157. if new_name.endswith('_id'):
  158. new_name = new_name[:-3]
  159. else:
  160. field_params['db_column'] = col_name
  161. new_name, num_repl = re.subn(r'\W', '_', new_name)
  162. if num_repl > 0:
  163. field_notes.append('Field renamed to remove unsuitable characters.')
  164. if new_name.find('__') >= 0:
  165. while new_name.find('__') >= 0:
  166. new_name = new_name.replace('__', '_')
  167. if col_name.lower().find('__') >= 0:
  168. # Only add the comment if the double underscore was in the original name
  169. field_notes.append("Field renamed because it contained more than one '_' in a row.")
  170. if new_name.startswith('_'):
  171. new_name = 'field%s' % new_name
  172. field_notes.append("Field renamed because it started with '_'.")
  173. if new_name.endswith('_'):
  174. new_name = '%sfield' % new_name
  175. field_notes.append("Field renamed because it ended with '_'.")
  176. if keyword.iskeyword(new_name):
  177. new_name += '_field'
  178. field_notes.append('Field renamed because it was a Python reserved word.')
  179. if new_name[0].isdigit():
  180. new_name = 'number_%s' % new_name
  181. field_notes.append("Field renamed because it wasn't a valid Python identifier.")
  182. if new_name in used_column_names:
  183. num = 0
  184. while '%s_%d' % (new_name, num) in used_column_names:
  185. num += 1
  186. new_name = '%s_%d' % (new_name, num)
  187. field_notes.append('Field renamed because of name conflict.')
  188. if col_name != new_name and field_notes:
  189. field_params['db_column'] = col_name
  190. return new_name, field_params, field_notes
  191. def get_field_type(self, connection, table_name, row):
  192. """
  193. Given the database connection, the table name, and the cursor row
  194. description, this routine will return the given field type name, as
  195. well as any additional keyword parameters and notes for the field.
  196. """
  197. field_params = OrderedDict()
  198. field_notes = []
  199. try:
  200. field_type = connection.introspection.get_field_type(row[1], row)
  201. except KeyError:
  202. field_type = 'TextField'
  203. field_notes.append('This field type is a guess.')
  204. # This is a hook for data_types_reverse to return a tuple of
  205. # (field_type, field_params_dict).
  206. if type(field_type) is tuple:
  207. field_type, new_params = field_type
  208. field_params.update(new_params)
  209. # Add max_length for all CharFields.
  210. if field_type == 'CharField' and row[3]:
  211. field_params['max_length'] = int(row[3])
  212. if field_type == 'DecimalField':
  213. if row[4] is None or row[5] is None:
  214. field_notes.append(
  215. 'max_digits and decimal_places have been guessed, as this '
  216. 'database handles decimal fields as float')
  217. field_params['max_digits'] = row[4] if row[4] is not None else 10
  218. field_params['decimal_places'] = row[5] if row[5] is not None else 5
  219. else:
  220. field_params['max_digits'] = row[4]
  221. field_params['decimal_places'] = row[5]
  222. return field_type, field_params, field_notes
  223. def get_meta(self, table_name, constraints, column_to_field_name):
  224. """
  225. Return a sequence comprising the lines of code necessary
  226. to construct the inner Meta class for the model corresponding
  227. to the given database table name.
  228. """
  229. unique_together = []
  230. for index, params in constraints.items():
  231. if params['unique']:
  232. columns = params['columns']
  233. if len(columns) > 1:
  234. # we do not want to include the u"" or u'' prefix
  235. # so we build the string rather than interpolate the tuple
  236. tup = '(' + ', '.join("'%s'" % column_to_field_name[c] for c in columns) + ')'
  237. unique_together.append(tup)
  238. meta = ["",
  239. " class Meta:",
  240. " managed = False",
  241. " db_table = '%s'" % table_name]
  242. if unique_together:
  243. tup = '(' + ', '.join(unique_together) + ',)'
  244. meta += [" unique_together = %s" % tup]
  245. return meta