Development of an internal social media platform with personalised dashboards for students
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.

inspectdb.py 13KB

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