inspectdb.py 13 KB

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