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.

introspection.py 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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 django_table_names(self, only_existing=False, include_views=True):
  46. """
  47. Return a list of all table names that have associated Django models and
  48. are in INSTALLED_APPS.
  49. If only_existing is True, include only the tables in the database.
  50. """
  51. from django.apps import apps
  52. from django.db import router
  53. tables = set()
  54. for app_config in apps.get_app_configs():
  55. for model in router.get_migratable_models(app_config, self.connection.alias):
  56. if not model._meta.managed:
  57. continue
  58. tables.add(model._meta.db_table)
  59. tables.update(
  60. f.m2m_db_table() for f in model._meta.local_many_to_many
  61. if f.remote_field.through._meta.managed
  62. )
  63. tables = list(tables)
  64. if only_existing:
  65. existing_tables = set(self.table_names(include_views=include_views))
  66. tables = [
  67. t
  68. for t in tables
  69. if self.identifier_converter(t) in existing_tables
  70. ]
  71. return tables
  72. def installed_models(self, tables):
  73. """
  74. Return a set of all models represented by the provided list of table
  75. names.
  76. """
  77. from django.apps import apps
  78. from django.db import router
  79. all_models = []
  80. for app_config in apps.get_app_configs():
  81. all_models.extend(router.get_migratable_models(app_config, self.connection.alias))
  82. tables = set(map(self.identifier_converter, tables))
  83. return {
  84. m for m in all_models
  85. if self.identifier_converter(m._meta.db_table) in tables
  86. }
  87. def sequence_list(self):
  88. """
  89. Return a list of information about all DB sequences for all models in
  90. all apps.
  91. """
  92. from django.apps import apps
  93. from django.db import router
  94. sequence_list = []
  95. with self.connection.cursor() as cursor:
  96. for app_config in apps.get_app_configs():
  97. for model in router.get_migratable_models(app_config, self.connection.alias):
  98. if not model._meta.managed:
  99. continue
  100. if model._meta.swapped:
  101. continue
  102. sequence_list.extend(self.get_sequences(cursor, model._meta.db_table, model._meta.local_fields))
  103. for f in model._meta.local_many_to_many:
  104. # If this is an m2m using an intermediate table,
  105. # we don't need to reset the sequence.
  106. if f.remote_field.through._meta.auto_created:
  107. sequence = self.get_sequences(cursor, f.m2m_db_table())
  108. sequence_list.extend(sequence or [{'table': f.m2m_db_table(), 'column': None}])
  109. return sequence_list
  110. def get_sequences(self, cursor, table_name, table_fields=()):
  111. """
  112. Return a list of introspected sequences for table_name. Each sequence
  113. is a dict: {'table': <table_name>, 'column': <column_name>}. An optional
  114. 'name' key can be added if the backend supports named sequences.
  115. """
  116. raise NotImplementedError('subclasses of BaseDatabaseIntrospection may require a get_sequences() method')
  117. def get_key_columns(self, cursor, table_name):
  118. """
  119. Backends can override this to return a list of:
  120. (column_name, referenced_table_name, referenced_column_name)
  121. for all key columns in given table.
  122. """
  123. raise NotImplementedError('subclasses of BaseDatabaseIntrospection may require a get_key_columns() method')
  124. def get_primary_key_column(self, cursor, table_name):
  125. """
  126. Return the name of the primary key column for the given table.
  127. """
  128. for constraint in self.get_constraints(cursor, table_name).values():
  129. if constraint['primary_key']:
  130. return constraint['columns'][0]
  131. return None
  132. def get_constraints(self, cursor, table_name):
  133. """
  134. Retrieve any constraints or keys (unique, pk, fk, check, index)
  135. across one or more columns.
  136. Return a dict mapping constraint names to their attributes,
  137. where attributes is a dict with keys:
  138. * columns: List of columns this covers
  139. * primary_key: True if primary key, False otherwise
  140. * unique: True if this is a unique constraint, False otherwise
  141. * foreign_key: (table, column) of target, or None
  142. * check: True if check constraint, False otherwise
  143. * index: True if index, False otherwise.
  144. * orders: The order (ASC/DESC) defined for the columns of indexes
  145. * type: The type of the index (btree, hash, etc.)
  146. Some backends may return special constraint names that don't exist
  147. if they don't name constraints of a certain type (e.g. SQLite)
  148. """
  149. raise NotImplementedError('subclasses of BaseDatabaseIntrospection may require a get_constraints() method')