introspection.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. from collections import namedtuple
  2. # Structure returned by DatabaseIntrospection.get_table_list()
  3. TableInfo = namedtuple('TableInfo', ['name', 'type'])
  4. # Structure returned by the DB-API cursor.description interface (PEP 249)
  5. FieldInfo = namedtuple('FieldInfo', 'name type_code display_size internal_size precision scale null_ok default')
  6. class BaseDatabaseIntrospection:
  7. """Encapsulate backend-specific introspection utilities."""
  8. data_types_reverse = {}
  9. def __init__(self, connection):
  10. self.connection = connection
  11. def get_field_type(self, data_type, description):
  12. """
  13. Hook for a database backend to use the cursor description to
  14. match a Django field type to a database column.
  15. For Oracle, the column data_type on its own is insufficient to
  16. distinguish between a FloatField and IntegerField, for example.
  17. """
  18. return self.data_types_reverse[data_type]
  19. def identifier_converter(self, name):
  20. """
  21. Apply a conversion to the identifier for the purposes of comparison.
  22. The default identifier converter is for case sensitive comparison.
  23. """
  24. return name
  25. def table_names(self, cursor=None, include_views=False):
  26. """
  27. Return a list of names of all tables that exist in the database.
  28. Sort the returned table list by Python's default sorting. Do NOT use
  29. the database's ORDER BY here to avoid subtle differences in sorting
  30. order between databases.
  31. """
  32. def get_names(cursor):
  33. return sorted(ti.name for ti in self.get_table_list(cursor)
  34. if include_views or ti.type == 't')
  35. if cursor is None:
  36. with self.connection.cursor() as cursor:
  37. return get_names(cursor)
  38. return get_names(cursor)
  39. def get_table_list(self, cursor):
  40. """
  41. Return an unsorted list of TableInfo named tuples of all tables and
  42. views that exist in the database.
  43. """
  44. raise NotImplementedError('subclasses of BaseDatabaseIntrospection may require a get_table_list() method')
  45. def get_migratable_models(self):
  46. from django.apps import apps
  47. from django.db import router
  48. return (
  49. model
  50. for app_config in apps.get_app_configs()
  51. for model in router.get_migratable_models(app_config, self.connection.alias)
  52. if model._meta.can_migrate(self.connection)
  53. )
  54. def django_table_names(self, only_existing=False, include_views=True):
  55. """
  56. Return a list of all table names that have associated Django models and
  57. are in INSTALLED_APPS.
  58. If only_existing is True, include only the tables in the database.
  59. """
  60. tables = set()
  61. for model in self.get_migratable_models():
  62. if not model._meta.managed:
  63. continue
  64. tables.add(model._meta.db_table)
  65. tables.update(
  66. f.m2m_db_table() for f in model._meta.local_many_to_many
  67. if f.remote_field.through._meta.managed
  68. )
  69. tables = list(tables)
  70. if only_existing:
  71. existing_tables = set(self.table_names(include_views=include_views))
  72. tables = [
  73. t
  74. for t in tables
  75. if self.identifier_converter(t) in existing_tables
  76. ]
  77. return tables
  78. def installed_models(self, tables):
  79. """
  80. Return a set of all models represented by the provided list of table
  81. names.
  82. """
  83. tables = set(map(self.identifier_converter, tables))
  84. return {
  85. m for m in self.get_migratable_models()
  86. if self.identifier_converter(m._meta.db_table) in tables
  87. }
  88. def sequence_list(self):
  89. """
  90. Return a list of information about all DB sequences for all models in
  91. all apps.
  92. """
  93. sequence_list = []
  94. with self.connection.cursor() as cursor:
  95. for model in self.get_migratable_models():
  96. if not model._meta.managed:
  97. continue
  98. if model._meta.swapped:
  99. continue
  100. sequence_list.extend(self.get_sequences(cursor, model._meta.db_table, model._meta.local_fields))
  101. for f in model._meta.local_many_to_many:
  102. # If this is an m2m using an intermediate table,
  103. # we don't need to reset the sequence.
  104. if f.remote_field.through._meta.auto_created:
  105. sequence = self.get_sequences(cursor, f.m2m_db_table())
  106. sequence_list.extend(sequence or [{'table': f.m2m_db_table(), 'column': None}])
  107. return sequence_list
  108. def get_sequences(self, cursor, table_name, table_fields=()):
  109. """
  110. Return a list of introspected sequences for table_name. Each sequence
  111. is a dict: {'table': <table_name>, 'column': <column_name>}. An optional
  112. 'name' key can be added if the backend supports named sequences.
  113. """
  114. raise NotImplementedError('subclasses of BaseDatabaseIntrospection may require a get_sequences() method')
  115. def get_key_columns(self, cursor, table_name):
  116. """
  117. Backends can override this to return a list of:
  118. (column_name, referenced_table_name, referenced_column_name)
  119. for all key columns in given table.
  120. """
  121. raise NotImplementedError('subclasses of BaseDatabaseIntrospection may require a get_key_columns() method')
  122. def get_primary_key_column(self, cursor, table_name):
  123. """
  124. Return the name of the primary key column for the given table.
  125. """
  126. for constraint in self.get_constraints(cursor, table_name).values():
  127. if constraint['primary_key']:
  128. return constraint['columns'][0]
  129. return None
  130. def get_constraints(self, cursor, table_name):
  131. """
  132. Retrieve any constraints or keys (unique, pk, fk, check, index)
  133. across one or more columns.
  134. Return a dict mapping constraint names to their attributes,
  135. where attributes is a dict with keys:
  136. * columns: List of columns this covers
  137. * primary_key: True if primary key, False otherwise
  138. * unique: True if this is a unique constraint, False otherwise
  139. * foreign_key: (table, column) of target, or None
  140. * check: True if check constraint, False otherwise
  141. * index: True if index, False otherwise.
  142. * orders: The order (ASC/DESC) defined for the columns of indexes
  143. * type: The type of the index (btree, hash, etc.)
  144. Some backends may return special constraint names that don't exist
  145. if they don't name constraints of a certain type (e.g. SQLite)
  146. """
  147. raise NotImplementedError('subclasses of BaseDatabaseIntrospection may require a get_constraints() method')