features.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. from django.db import ProgrammingError
  2. from django.utils.functional import cached_property
  3. class BaseDatabaseFeatures:
  4. # An optional tuple indicating the minimum supported database version.
  5. minimum_database_version = None
  6. gis_enabled = False
  7. # Oracle can't group by LOB (large object) data types.
  8. allows_group_by_lob = True
  9. allows_group_by_selected_pks = False
  10. allows_group_by_select_index = True
  11. empty_fetchmany_value = []
  12. update_can_self_select = True
  13. # Does the backend support self-reference subqueries in the DELETE
  14. # statement?
  15. delete_can_self_reference_subquery = True
  16. # Does the backend distinguish between '' and None?
  17. interprets_empty_strings_as_nulls = False
  18. # Does the backend allow inserting duplicate NULL rows in a nullable
  19. # unique field? All core backends implement this correctly, but other
  20. # databases such as SQL Server do not.
  21. supports_nullable_unique_constraints = True
  22. # Does the backend allow inserting duplicate rows when a unique_together
  23. # constraint exists and some fields are nullable but not all of them?
  24. supports_partially_nullable_unique_constraints = True
  25. # Does the backend supports specifying whether NULL values should be
  26. # considered distinct in unique constraints?
  27. supports_nulls_distinct_unique_constraints = False
  28. # Does the backend support initially deferrable unique constraints?
  29. supports_deferrable_unique_constraints = False
  30. can_use_chunked_reads = True
  31. can_return_columns_from_insert = False
  32. can_return_rows_from_bulk_insert = False
  33. can_return_rows_from_update = False
  34. has_bulk_insert = True
  35. uses_savepoints = True
  36. can_release_savepoints = False
  37. # If True, don't use integer foreign keys referring to, e.g., positive
  38. # integer primary keys.
  39. related_fields_match_type = False
  40. allow_sliced_subqueries_with_in = True
  41. has_select_for_update = False
  42. has_select_for_update_nowait = False
  43. has_select_for_update_skip_locked = False
  44. has_select_for_update_of = False
  45. has_select_for_no_key_update = False
  46. # Does the database's SELECT FOR UPDATE OF syntax require a column rather
  47. # than a table?
  48. select_for_update_of_column = False
  49. # Does the default test database allow multiple connections?
  50. # Usually an indication that the test database is in-memory
  51. test_db_allows_multiple_connections = True
  52. # Can an object be saved without an explicit primary key?
  53. supports_unspecified_pk = False
  54. # Can a fixture contain forward references? i.e., are
  55. # FK constraints checked at the end of transaction, or
  56. # at the end of each save operation?
  57. supports_forward_references = True
  58. # Does the backend truncate names properly when they are too long?
  59. truncates_names = False
  60. # Is there a REAL datatype in addition to floats/doubles?
  61. has_real_datatype = False
  62. supports_subqueries_in_group_by = True
  63. # Does the backend ignore unnecessary ORDER BY clauses in subqueries?
  64. ignores_unnecessary_order_by_in_subqueries = True
  65. # Is there a true datatype for boolean?
  66. has_native_boolean_field = False
  67. # Is there a true datatype for uuid?
  68. has_native_uuid_field = False
  69. # Is there a true datatype for timedeltas?
  70. has_native_duration_field = False
  71. # Does the database driver supports same type temporal data subtraction
  72. # by returning the type used to store duration field?
  73. supports_temporal_subtraction = False
  74. # Does the __regex lookup support backreferencing and grouping?
  75. supports_regex_backreferencing = True
  76. # Can date/datetime lookups be performed using a string?
  77. supports_date_lookup_using_string = True
  78. # Can datetimes with timezones be used?
  79. supports_timezones = True
  80. # Does the database have a copy of the zoneinfo database?
  81. has_zoneinfo_database = True
  82. # When performing a GROUP BY, is an ORDER BY NULL required
  83. # to remove any ordering?
  84. requires_explicit_null_ordering_when_grouping = False
  85. # Does the backend order NULL values as largest or smallest?
  86. nulls_order_largest = False
  87. # Does the backend support NULLS FIRST and NULLS LAST in ORDER BY?
  88. supports_order_by_nulls_modifier = True
  89. # Does the backend orders NULLS FIRST by default?
  90. order_by_nulls_first = False
  91. # The database's limit on the number of query parameters.
  92. max_query_params = None
  93. # Can an object have an autoincrement primary key of 0?
  94. allows_auto_pk_0 = True
  95. # Do we need to NULL a ForeignKey out, or can the constraint check be
  96. # deferred
  97. can_defer_constraint_checks = False
  98. # Does the backend support tablespaces? Default to False because it isn't
  99. # in the SQL standard.
  100. supports_tablespaces = False
  101. # Does the backend reset sequences between tests?
  102. supports_sequence_reset = True
  103. # Can the backend introspect the default value of a column?
  104. can_introspect_default = True
  105. # Confirm support for introspected foreign keys
  106. # Every database can do this reliably, except MySQL,
  107. # which can't do it for MyISAM tables
  108. can_introspect_foreign_keys = True
  109. # Map fields which some backends may not be able to differentiate to the
  110. # field it's introspected as.
  111. introspected_field_types = {
  112. "AutoField": "AutoField",
  113. "BigAutoField": "BigAutoField",
  114. "BigIntegerField": "BigIntegerField",
  115. "BinaryField": "BinaryField",
  116. "BooleanField": "BooleanField",
  117. "CharField": "CharField",
  118. "DurationField": "DurationField",
  119. "GenericIPAddressField": "GenericIPAddressField",
  120. "IntegerField": "IntegerField",
  121. "PositiveBigIntegerField": "PositiveBigIntegerField",
  122. "PositiveIntegerField": "PositiveIntegerField",
  123. "PositiveSmallIntegerField": "PositiveSmallIntegerField",
  124. "SmallAutoField": "SmallAutoField",
  125. "SmallIntegerField": "SmallIntegerField",
  126. "TimeField": "TimeField",
  127. }
  128. # Can the backend introspect the column order (ASC/DESC) for indexes?
  129. supports_index_column_ordering = True
  130. # Does the backend support introspection of materialized views?
  131. can_introspect_materialized_views = False
  132. # Support for the DISTINCT ON clause
  133. can_distinct_on_fields = False
  134. # Does the backend prevent running SQL queries in broken transactions?
  135. atomic_transactions = True
  136. # Can we roll back DDL in a transaction?
  137. can_rollback_ddl = False
  138. schema_editor_uses_clientside_param_binding = False
  139. # Can we issue more than one ALTER COLUMN clause in an ALTER TABLE?
  140. supports_combined_alters = False
  141. # Does it support foreign keys?
  142. supports_foreign_keys = True
  143. # Can it create foreign key constraints inline when adding columns?
  144. can_create_inline_fk = True
  145. # Can an index be renamed?
  146. can_rename_index = False
  147. # Does it automatically index foreign keys?
  148. indexes_foreign_keys = True
  149. # Does it support CHECK constraints?
  150. supports_column_check_constraints = True
  151. supports_table_check_constraints = True
  152. # Does the backend support introspection of CHECK constraints?
  153. can_introspect_check_constraints = True
  154. # Does the backend support 'pyformat' style:
  155. # ("... %(name)s ...", {'name': value})
  156. # parameter passing? Note this can be provided by the backend even if not
  157. # supported by the Python driver
  158. supports_paramstyle_pyformat = True
  159. # Does the backend require literal defaults, rather than parameterized
  160. # ones?
  161. requires_literal_defaults = False
  162. # Does the backend support functions in defaults?
  163. supports_expression_defaults = True
  164. # Does the backend support the DEFAULT keyword in insert queries?
  165. supports_default_keyword_in_insert = True
  166. # Does the backend support the DEFAULT keyword in bulk insert queries?
  167. supports_default_keyword_in_bulk_insert = True
  168. # Does the backend require a connection reset after each material schema
  169. # change?
  170. connection_persists_old_columns = False
  171. # What kind of error does the backend throw when accessing closed cursor?
  172. closed_cursor_error_class = ProgrammingError
  173. # Does 'a' LIKE 'A' match?
  174. has_case_insensitive_like = False
  175. # Suffix for backends that don't support "SELECT xxx;" queries.
  176. bare_select_suffix = ""
  177. # If NULL is implied on columns without needing to be explicitly specified
  178. implied_column_null = False
  179. # Does the backend support "select for update" queries with limit (and
  180. # offset)?
  181. supports_select_for_update_with_limit = True
  182. # Does the backend ignore null expressions in GREATEST and LEAST queries
  183. # unless every expression is null?
  184. greatest_least_ignores_nulls = False
  185. # Can the backend clone databases for parallel test execution?
  186. # Defaults to False to allow third-party backends to opt-in.
  187. can_clone_databases = False
  188. # Does the backend consider table names with different casing to
  189. # be equal?
  190. ignores_table_name_case = False
  191. # Place FOR UPDATE right after FROM clause. Used on MSSQL.
  192. for_update_after_from = False
  193. # Combinatorial flags
  194. supports_select_union = True
  195. supports_select_intersection = True
  196. supports_select_difference = True
  197. supports_slicing_ordering_in_compound = False
  198. supports_parentheses_in_compound = True
  199. requires_compound_order_by_subquery = False
  200. # Does the database support SQL 2003 FILTER (WHERE ...) in aggregate
  201. # expressions?
  202. supports_aggregate_filter_clause = False
  203. # Does the database support ORDER BY in aggregate expressions?
  204. supports_aggregate_order_by_clause = False
  205. # Does the database backend support DISTINCT when using multiple arguments
  206. # in an aggregate expression? For example, Sqlite treats the "delimiter"
  207. # argument of STRING_AGG/GROUP_CONCAT as an extra argument and does not
  208. # allow using a custom delimiter along with DISTINCT.
  209. supports_aggregate_distinct_multiple_argument = True
  210. # Does the database support SQL 2023 ANY_VALUE in GROUP BY?
  211. supports_any_value = False
  212. # Does the database support bitwise aggregations: BIT_AND, BIT_OR, and
  213. # BIT_XOR?
  214. supports_bit_aggregations = True
  215. # Does the backend support the default parameter in bitwise aggregations?
  216. supports_default_in_bit_aggregations = True
  217. # Does the backend support indexing a TextField?
  218. supports_index_on_text_field = True
  219. # Does the backend support window expressions (expression OVER (...))?
  220. supports_over_clause = False
  221. supports_frame_range_fixed_distance = False
  222. supports_frame_exclusion = False
  223. only_supports_unbounded_with_preceding_and_following = False
  224. # Does the backend support CAST with precision?
  225. supports_cast_with_precision = True
  226. # How many second decimals does the database return when casting a value to
  227. # a type with time?
  228. time_cast_precision = 6
  229. # SQL to create a procedure for use by the Django test suite. The
  230. # functionality of the procedure isn't important.
  231. create_test_procedure_without_params_sql = None
  232. create_test_procedure_with_int_param_sql = None
  233. # Does the backend support keyword parameters for cursor.callproc()?
  234. supports_callproc_kwargs = False
  235. # What formats does the backend EXPLAIN syntax support?
  236. supported_explain_formats = set()
  237. # Does the backend support the default parameter in lead() and lag()?
  238. supports_default_in_lead_lag = True
  239. # Does the backend support ignoring constraint or uniqueness errors during
  240. # INSERT?
  241. supports_ignore_conflicts = True
  242. # Does the backend support updating rows on constraint or uniqueness errors
  243. # during INSERT?
  244. supports_update_conflicts = False
  245. supports_update_conflicts_with_target = False
  246. # Does this backend require casting the results of CASE expressions used
  247. # in UPDATE statements to ensure the expression has the correct type?
  248. requires_casted_case_in_updates = False
  249. # Does the backend support partial indexes (CREATE INDEX ... WHERE ...)?
  250. supports_partial_indexes = True
  251. supports_functions_in_partial_indexes = True
  252. # Does the backend support covering indexes (CREATE INDEX ... INCLUDE ...)?
  253. supports_covering_indexes = False
  254. # Does the backend support indexes on expressions?
  255. supports_expression_indexes = True
  256. # Does the backend treat COLLATE as an indexed expression?
  257. collate_as_index_expression = False
  258. # Does the database allow more than one constraint or index on the same
  259. # field(s)?
  260. allows_multiple_constraints_on_same_fields = True
  261. # Does the backend support boolean expressions in SELECT and GROUP BY
  262. # clauses?
  263. supports_boolean_expr_in_select_clause = True
  264. # Does the backend support comparing boolean expressions in WHERE clauses?
  265. # Eg: WHERE (price > 0) IS NOT NULL
  266. supports_comparing_boolean_expr = True
  267. # Does the backend support JSONField?
  268. supports_json_field = True
  269. # Can the backend introspect a JSONField?
  270. can_introspect_json_field = True
  271. # Does the backend support primitives in JSONField?
  272. supports_primitives_in_json_field = True
  273. # Is there a true datatype for JSON?
  274. has_native_json_field = False
  275. # Does the backend use PostgreSQL-style JSON operators like '->'?
  276. has_json_operators = False
  277. # Does the backend support __contains and __contained_by lookups for
  278. # a JSONField?
  279. supports_json_field_contains = True
  280. # Does value__d__contains={'f': 'g'} (without a list around the dict) match
  281. # {'d': [{'f': 'g'}]}?
  282. json_key_contains_list_matching_requires_list = False
  283. # Does the backend support JSONObject() database function?
  284. has_json_object_function = True
  285. # Does the backend support negative JSON array indexing?
  286. supports_json_negative_indexing = True
  287. # Does the backend support column collations?
  288. supports_collation_on_charfield = True
  289. supports_collation_on_textfield = True
  290. # Does the backend support non-deterministic collations?
  291. supports_non_deterministic_collations = True
  292. # Does the backend support column and table comments?
  293. supports_comments = False
  294. # Does the backend support column comments in ADD COLUMN statements?
  295. supports_comments_inline = False
  296. # Does the backend support stored generated columns?
  297. supports_stored_generated_columns = False
  298. # Does the backend support virtual generated columns?
  299. supports_virtual_generated_columns = False
  300. # Does the backend support altering data types of generated columns?
  301. supports_alter_generated_column_data_type = True
  302. # Does the backend support the logical XOR operator?
  303. supports_logical_xor = False
  304. # Set to (exception, message) if null characters in text are disallowed.
  305. prohibits_null_characters_in_text_exception = None
  306. # Does the backend support unlimited character columns?
  307. supports_unlimited_charfield = False
  308. # Does the backend support numeric columns with no precision?
  309. supports_no_precision_decimalfield = False
  310. # Does the backend support native tuple lookups (=, >, <, IN)?
  311. supports_tuple_lookups = True
  312. # Does the backend support native tuple gt(e), lt(e) comparisons against
  313. # subqueries?
  314. supports_tuple_comparison_against_subquery = True
  315. # Does the backend support CASCADE, DEFAULT, NULL as delete options?
  316. supports_on_delete_db_cascade = True
  317. supports_on_delete_db_default = True
  318. supports_on_delete_db_null = True
  319. # Does the backend support the inspectdb management command?
  320. supports_inspectdb = True
  321. # Collation names for use by the Django test suite.
  322. test_collations = {
  323. "ci": None, # Case-insensitive.
  324. "cs": None, # Case-sensitive.
  325. "non_default": None, # Non-default.
  326. "swedish_ci": None, # Swedish case-insensitive.
  327. "virtual": None, # A collation that can be used for virtual columns.
  328. }
  329. # SQL template override for tests.aggregation.tests.NowUTC
  330. test_now_utc_template = None
  331. # SQL to create a model instance using the database defaults.
  332. insert_test_table_with_defaults = None
  333. # Does the Round() database function round to even?
  334. rounds_to_even = False
  335. # Should PatternLookup.process_rhs() use self.param_pattern? It's unneeded
  336. # on databases that don't use LIKE for pattern matching.
  337. pattern_lookup_needs_param_pattern = True
  338. # A set of dotted paths to tests in Django's test suite that are expected
  339. # to fail on this database.
  340. django_test_expected_failures = set()
  341. # A map of reasons to sets of dotted paths to tests in Django's test suite
  342. # that should be skipped for this database.
  343. django_test_skips = {}
  344. # DatabaseWrapper methods that should raise an error if accessed in
  345. # django.test.SimpleTestCase.
  346. disallowed_simple_test_case_connection_methods = [
  347. ("connect", "connections"),
  348. ("temporary_connection", "connections"),
  349. ("cursor", "queries"),
  350. ("chunked_cursor", "queries"),
  351. ]
  352. supports_uuid4_function = False
  353. supports_uuid4_function_in_default = False
  354. supports_uuid7_function = False
  355. supports_uuid7_function_shift = False
  356. def __init__(self, connection):
  357. self.connection = connection
  358. def __del__(self):
  359. del self.connection
  360. @cached_property
  361. def supports_explaining_query_execution(self):
  362. """Does this backend support explaining query execution?"""
  363. return self.connection.ops.explain_prefix is not None
  364. @cached_property
  365. def supports_transactions(self):
  366. """Confirm support for transactions."""
  367. with self.connection.cursor() as cursor:
  368. cursor.execute("CREATE TABLE ROLLBACK_TEST (X INT)")
  369. self.connection.set_autocommit(False)
  370. cursor.execute("INSERT INTO ROLLBACK_TEST (X) VALUES (8)")
  371. self.connection.rollback()
  372. self.connection.set_autocommit(True)
  373. cursor.execute("SELECT COUNT(X) FROM ROLLBACK_TEST")
  374. (count,) = cursor.fetchone()
  375. cursor.execute("DROP TABLE ROLLBACK_TEST")
  376. return count == 0
  377. def allows_group_by_selected_pks_on_model(self, model):
  378. if not self.allows_group_by_selected_pks:
  379. return False
  380. return model._meta.managed