2
0

tests.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. """Tests related to django.db.backends that haven't been organized."""
  2. import datetime
  3. import threading
  4. import unittest
  5. import warnings
  6. from unittest import mock
  7. from django.core.management.color import no_style
  8. from django.db import (
  9. DEFAULT_DB_ALIAS,
  10. DatabaseError,
  11. IntegrityError,
  12. connection,
  13. connections,
  14. reset_queries,
  15. transaction,
  16. )
  17. from django.db.backends.base.base import BaseDatabaseWrapper
  18. from django.db.backends.signals import connection_created
  19. from django.db.backends.utils import CursorWrapper
  20. from django.db.models.sql.constants import CURSOR
  21. from django.test import (
  22. TestCase,
  23. TransactionTestCase,
  24. override_settings,
  25. skipIfDBFeature,
  26. skipUnlessDBFeature,
  27. )
  28. from .models import (
  29. Article,
  30. Object,
  31. ObjectReference,
  32. Person,
  33. Post,
  34. RawData,
  35. Reporter,
  36. ReporterProxy,
  37. SchoolClass,
  38. SQLKeywordsModel,
  39. Square,
  40. VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ,
  41. )
  42. class DateQuotingTest(TestCase):
  43. def test_django_date_trunc(self):
  44. """
  45. Test the custom ``django_date_trunc method``, in particular against
  46. fields which clash with strings passed to it (e.g. 'year') (#12818).
  47. """
  48. updated = datetime.datetime(2010, 2, 20)
  49. SchoolClass.objects.create(year=2009, last_updated=updated)
  50. years = SchoolClass.objects.dates("last_updated", "year")
  51. self.assertEqual(list(years), [datetime.date(2010, 1, 1)])
  52. def test_django_date_extract(self):
  53. """
  54. Test the custom ``django_date_extract method``, in particular against fields
  55. which clash with strings passed to it (e.g. 'day') (#12818).
  56. """
  57. updated = datetime.datetime(2010, 2, 20)
  58. SchoolClass.objects.create(year=2009, last_updated=updated)
  59. classes = SchoolClass.objects.filter(last_updated__day=20)
  60. self.assertEqual(len(classes), 1)
  61. @override_settings(DEBUG=True)
  62. class LastExecutedQueryTest(TestCase):
  63. def test_last_executed_query_without_previous_query(self):
  64. """
  65. last_executed_query should not raise an exception even if no previous
  66. query has been run.
  67. """
  68. suffix = connection.features.bare_select_suffix
  69. with connection.cursor() as cursor:
  70. if connection.vendor == "oracle":
  71. cursor.statement = None
  72. # No previous query has been run.
  73. connection.ops.last_executed_query(cursor, "", ())
  74. # Previous query crashed.
  75. connection.ops.last_executed_query(cursor, "SELECT %s" + suffix, (1,))
  76. def test_debug_sql(self):
  77. qs = Reporter.objects.filter(first_name="test")
  78. ops = connections[qs.db].ops
  79. with mock.patch.object(ops, "format_debug_sql") as format_debug_sql:
  80. list(qs)
  81. # Queries are formatted with DatabaseOperations.format_debug_sql().
  82. format_debug_sql.assert_called()
  83. sql = connection.queries[-1]["sql"].lower()
  84. self.assertIn("select", sql)
  85. self.assertIn(Reporter._meta.db_table, sql)
  86. def test_query_encoding(self):
  87. """last_executed_query() returns a string."""
  88. data = RawData.objects.filter(raw_data=b"\x00\x46 \xFE").extra(
  89. select={"föö": 1}
  90. )
  91. sql, params = data.query.sql_with_params()
  92. with data.query.get_compiler("default").execute_sql(CURSOR) as cursor:
  93. last_sql = cursor.db.ops.last_executed_query(cursor, sql, params)
  94. self.assertIsInstance(last_sql, str)
  95. def test_last_executed_query(self):
  96. # last_executed_query() interpolate all parameters, in most cases it is
  97. # not equal to QuerySet.query.
  98. for qs in (
  99. Article.objects.filter(pk=1),
  100. Article.objects.filter(pk__in=(1, 2), reporter__pk=3),
  101. Article.objects.filter(
  102. pk=1,
  103. reporter__pk=9,
  104. ).exclude(reporter__pk__in=[2, 1]),
  105. Article.objects.filter(pk__in=list(range(20, 31))),
  106. ):
  107. sql, params = qs.query.sql_with_params()
  108. with qs.query.get_compiler(DEFAULT_DB_ALIAS).execute_sql(CURSOR) as cursor:
  109. self.assertEqual(
  110. cursor.db.ops.last_executed_query(cursor, sql, params),
  111. str(qs.query),
  112. )
  113. @skipUnlessDBFeature("supports_paramstyle_pyformat")
  114. def test_last_executed_query_dict(self):
  115. square_opts = Square._meta
  116. sql = "INSERT INTO %s (%s, %s) VALUES (%%(root)s, %%(square)s)" % (
  117. connection.introspection.identifier_converter(square_opts.db_table),
  118. connection.ops.quote_name(square_opts.get_field("root").column),
  119. connection.ops.quote_name(square_opts.get_field("square").column),
  120. )
  121. with connection.cursor() as cursor:
  122. params = {"root": 2, "square": 4}
  123. cursor.execute(sql, params)
  124. self.assertEqual(
  125. cursor.db.ops.last_executed_query(cursor, sql, params),
  126. sql % params,
  127. )
  128. @skipUnlessDBFeature("supports_paramstyle_pyformat")
  129. def test_last_executed_query_dict_overlap_keys(self):
  130. square_opts = Square._meta
  131. sql = "INSERT INTO %s (%s, %s) VALUES (%%(root)s, %%(root2)s)" % (
  132. connection.introspection.identifier_converter(square_opts.db_table),
  133. connection.ops.quote_name(square_opts.get_field("root").column),
  134. connection.ops.quote_name(square_opts.get_field("square").column),
  135. )
  136. with connection.cursor() as cursor:
  137. params = {"root": 2, "root2": 4}
  138. cursor.execute(sql, params)
  139. self.assertEqual(
  140. cursor.db.ops.last_executed_query(cursor, sql, params),
  141. sql % params,
  142. )
  143. def test_last_executed_query_with_duplicate_params(self):
  144. square_opts = Square._meta
  145. table = connection.introspection.identifier_converter(square_opts.db_table)
  146. id_column = connection.ops.quote_name(square_opts.get_field("id").column)
  147. root_column = connection.ops.quote_name(square_opts.get_field("root").column)
  148. sql = f"UPDATE {table} SET {root_column} = %s + %s WHERE {id_column} = %s"
  149. with connection.cursor() as cursor:
  150. params = [42, 42, 1]
  151. cursor.execute(sql, params)
  152. last_executed_query = connection.ops.last_executed_query(
  153. cursor, sql, params
  154. )
  155. self.assertEqual(
  156. last_executed_query,
  157. f"UPDATE {table} SET {root_column} = 42 + 42 WHERE {id_column} = 1",
  158. )
  159. class ParameterHandlingTest(TestCase):
  160. def test_bad_parameter_count(self):
  161. """
  162. An executemany call with too many/not enough parameters will raise an
  163. exception.
  164. """
  165. with connection.cursor() as cursor:
  166. query = "INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % (
  167. connection.introspection.identifier_converter("backends_square"),
  168. connection.ops.quote_name("root"),
  169. connection.ops.quote_name("square"),
  170. )
  171. with self.assertRaises(Exception):
  172. cursor.executemany(query, [(1, 2, 3)])
  173. with self.assertRaises(Exception):
  174. cursor.executemany(query, [(1,)])
  175. class LongNameTest(TransactionTestCase):
  176. """Long primary keys and model names can result in a sequence name
  177. that exceeds the database limits, which will result in truncation
  178. on certain databases (e.g., Postgres). The backend needs to use
  179. the correct sequence name in last_insert_id and other places, so
  180. check it is. Refs #8901.
  181. """
  182. available_apps = ["backends"]
  183. def test_sequence_name_length_limits_create(self):
  184. """Creation of model with long name and long pk name doesn't error."""
  185. VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
  186. def test_sequence_name_length_limits_m2m(self):
  187. """
  188. An m2m save of a model with a long name and a long m2m field name
  189. doesn't error (#8901).
  190. """
  191. obj = (
  192. VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
  193. )
  194. rel_obj = Person.objects.create(first_name="Django", last_name="Reinhardt")
  195. obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj)
  196. def test_sequence_name_length_limits_flush(self):
  197. """
  198. Sequence resetting as part of a flush with model with long name and
  199. long pk name doesn't error (#8901).
  200. """
  201. # A full flush is expensive to the full test, so we dig into the
  202. # internals to generate the likely offending SQL and run it manually
  203. # Some convenience aliases
  204. VLM = VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
  205. VLM_m2m = (
  206. VLM.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.through
  207. )
  208. tables = [
  209. VLM._meta.db_table,
  210. VLM_m2m._meta.db_table,
  211. ]
  212. sql_list = connection.ops.sql_flush(no_style(), tables, reset_sequences=True)
  213. connection.ops.execute_sql_flush(sql_list)
  214. @skipUnlessDBFeature("supports_sequence_reset")
  215. class SequenceResetTest(TestCase):
  216. def test_generic_relation(self):
  217. "Sequence names are correct when resetting generic relations (Ref #13941)"
  218. # Create an object with a manually specified PK
  219. Post.objects.create(id=10, name="1st post", text="hello world")
  220. # Reset the sequences for the database
  221. commands = connections[DEFAULT_DB_ALIAS].ops.sequence_reset_sql(
  222. no_style(), [Post]
  223. )
  224. with connection.cursor() as cursor:
  225. for sql in commands:
  226. cursor.execute(sql)
  227. # If we create a new object now, it should have a PK greater
  228. # than the PK we specified manually.
  229. obj = Post.objects.create(name="New post", text="goodbye world")
  230. self.assertGreater(obj.pk, 10)
  231. # This test needs to run outside of a transaction, otherwise closing the
  232. # connection would implicitly rollback and cause problems during teardown.
  233. class ConnectionCreatedSignalTest(TransactionTestCase):
  234. available_apps = []
  235. # Unfortunately with sqlite3 the in-memory test database cannot be closed,
  236. # and so it cannot be re-opened during testing.
  237. @skipUnlessDBFeature("test_db_allows_multiple_connections")
  238. def test_signal(self):
  239. data = {}
  240. def receiver(sender, connection, **kwargs):
  241. data["connection"] = connection
  242. connection_created.connect(receiver)
  243. connection.close()
  244. with connection.cursor():
  245. pass
  246. self.assertIs(data["connection"].connection, connection.connection)
  247. connection_created.disconnect(receiver)
  248. data.clear()
  249. with connection.cursor():
  250. pass
  251. self.assertEqual(data, {})
  252. class EscapingChecks(TestCase):
  253. """
  254. All tests in this test case are also run with settings.DEBUG=True in
  255. EscapingChecksDebug test case, to also test CursorDebugWrapper.
  256. """
  257. bare_select_suffix = connection.features.bare_select_suffix
  258. def test_paramless_no_escaping(self):
  259. with connection.cursor() as cursor:
  260. cursor.execute("SELECT '%s'" + self.bare_select_suffix)
  261. self.assertEqual(cursor.fetchall()[0][0], "%s")
  262. def test_parameter_escaping(self):
  263. with connection.cursor() as cursor:
  264. cursor.execute("SELECT '%%', %s" + self.bare_select_suffix, ("%d",))
  265. self.assertEqual(cursor.fetchall()[0], ("%", "%d"))
  266. @override_settings(DEBUG=True)
  267. class EscapingChecksDebug(EscapingChecks):
  268. pass
  269. class BackendTestCase(TransactionTestCase):
  270. available_apps = ["backends"]
  271. def create_squares_with_executemany(self, args):
  272. self.create_squares(args, "format", True)
  273. def create_squares(self, args, paramstyle, multiple):
  274. opts = Square._meta
  275. tbl = connection.introspection.identifier_converter(opts.db_table)
  276. f1 = connection.ops.quote_name(opts.get_field("root").column)
  277. f2 = connection.ops.quote_name(opts.get_field("square").column)
  278. if paramstyle == "format":
  279. query = "INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % (tbl, f1, f2)
  280. elif paramstyle == "pyformat":
  281. query = "INSERT INTO %s (%s, %s) VALUES (%%(root)s, %%(square)s)" % (
  282. tbl,
  283. f1,
  284. f2,
  285. )
  286. else:
  287. raise ValueError("unsupported paramstyle in test")
  288. with connection.cursor() as cursor:
  289. if multiple:
  290. cursor.executemany(query, args)
  291. else:
  292. cursor.execute(query, args)
  293. def test_cursor_executemany(self):
  294. # Test cursor.executemany #4896
  295. args = [(i, i**2) for i in range(-5, 6)]
  296. self.create_squares_with_executemany(args)
  297. self.assertEqual(Square.objects.count(), 11)
  298. for i in range(-5, 6):
  299. square = Square.objects.get(root=i)
  300. self.assertEqual(square.square, i**2)
  301. def test_cursor_executemany_with_empty_params_list(self):
  302. # Test executemany with params=[] does nothing #4765
  303. args = []
  304. self.create_squares_with_executemany(args)
  305. self.assertEqual(Square.objects.count(), 0)
  306. def test_cursor_executemany_with_iterator(self):
  307. # Test executemany accepts iterators #10320
  308. args = ((i, i**2) for i in range(-3, 2))
  309. self.create_squares_with_executemany(args)
  310. self.assertEqual(Square.objects.count(), 5)
  311. args = ((i, i**2) for i in range(3, 7))
  312. with override_settings(DEBUG=True):
  313. # same test for DebugCursorWrapper
  314. self.create_squares_with_executemany(args)
  315. self.assertEqual(Square.objects.count(), 9)
  316. @skipUnlessDBFeature("supports_paramstyle_pyformat")
  317. def test_cursor_execute_with_pyformat(self):
  318. # Support pyformat style passing of parameters #10070
  319. args = {"root": 3, "square": 9}
  320. self.create_squares(args, "pyformat", multiple=False)
  321. self.assertEqual(Square.objects.count(), 1)
  322. @skipUnlessDBFeature("supports_paramstyle_pyformat")
  323. def test_cursor_executemany_with_pyformat(self):
  324. # Support pyformat style passing of parameters #10070
  325. args = [{"root": i, "square": i**2} for i in range(-5, 6)]
  326. self.create_squares(args, "pyformat", multiple=True)
  327. self.assertEqual(Square.objects.count(), 11)
  328. for i in range(-5, 6):
  329. square = Square.objects.get(root=i)
  330. self.assertEqual(square.square, i**2)
  331. @skipUnlessDBFeature("supports_paramstyle_pyformat")
  332. def test_cursor_executemany_with_pyformat_iterator(self):
  333. args = ({"root": i, "square": i**2} for i in range(-3, 2))
  334. self.create_squares(args, "pyformat", multiple=True)
  335. self.assertEqual(Square.objects.count(), 5)
  336. args = ({"root": i, "square": i**2} for i in range(3, 7))
  337. with override_settings(DEBUG=True):
  338. # same test for DebugCursorWrapper
  339. self.create_squares(args, "pyformat", multiple=True)
  340. self.assertEqual(Square.objects.count(), 9)
  341. def test_unicode_fetches(self):
  342. # fetchone, fetchmany, fetchall return strings as Unicode objects.
  343. qn = connection.ops.quote_name
  344. Person(first_name="John", last_name="Doe").save()
  345. Person(first_name="Jane", last_name="Doe").save()
  346. Person(first_name="Mary", last_name="Agnelline").save()
  347. Person(first_name="Peter", last_name="Parker").save()
  348. Person(first_name="Clark", last_name="Kent").save()
  349. opts2 = Person._meta
  350. f3, f4 = opts2.get_field("first_name"), opts2.get_field("last_name")
  351. with connection.cursor() as cursor:
  352. cursor.execute(
  353. "SELECT %s, %s FROM %s ORDER BY %s"
  354. % (
  355. qn(f3.column),
  356. qn(f4.column),
  357. connection.introspection.identifier_converter(opts2.db_table),
  358. qn(f3.column),
  359. )
  360. )
  361. self.assertEqual(cursor.fetchone(), ("Clark", "Kent"))
  362. self.assertEqual(
  363. list(cursor.fetchmany(2)), [("Jane", "Doe"), ("John", "Doe")]
  364. )
  365. self.assertEqual(
  366. list(cursor.fetchall()), [("Mary", "Agnelline"), ("Peter", "Parker")]
  367. )
  368. def test_unicode_password(self):
  369. old_password = connection.settings_dict["PASSWORD"]
  370. connection.settings_dict["PASSWORD"] = "françois"
  371. try:
  372. with connection.cursor():
  373. pass
  374. except DatabaseError:
  375. # As password is probably wrong, a database exception is expected
  376. pass
  377. except Exception as e:
  378. self.fail("Unexpected error raised with Unicode password: %s" % e)
  379. finally:
  380. connection.settings_dict["PASSWORD"] = old_password
  381. def test_database_operations_helper_class(self):
  382. # Ticket #13630
  383. self.assertTrue(hasattr(connection, "ops"))
  384. self.assertTrue(hasattr(connection.ops, "connection"))
  385. self.assertEqual(connection, connection.ops.connection)
  386. def test_database_operations_init(self):
  387. """
  388. DatabaseOperations initialization doesn't query the database.
  389. See #17656.
  390. """
  391. with self.assertNumQueries(0):
  392. connection.ops.__class__(connection)
  393. def test_cached_db_features(self):
  394. self.assertIn(connection.features.supports_transactions, (True, False))
  395. self.assertIn(connection.features.can_introspect_foreign_keys, (True, False))
  396. def test_duplicate_table_error(self):
  397. """Creating an existing table returns a DatabaseError"""
  398. query = "CREATE TABLE %s (id INTEGER);" % Article._meta.db_table
  399. with connection.cursor() as cursor:
  400. with self.assertRaises(DatabaseError):
  401. cursor.execute(query)
  402. def test_cursor_contextmanager(self):
  403. """
  404. Cursors can be used as a context manager
  405. """
  406. with connection.cursor() as cursor:
  407. self.assertIsInstance(cursor, CursorWrapper)
  408. # Both InterfaceError and ProgrammingError seem to be used when
  409. # accessing closed cursor (psycopg has InterfaceError, rest seem
  410. # to use ProgrammingError).
  411. with self.assertRaises(connection.features.closed_cursor_error_class):
  412. # cursor should be closed, so no queries should be possible.
  413. cursor.execute("SELECT 1" + connection.features.bare_select_suffix)
  414. @unittest.skipUnless(
  415. connection.vendor == "postgresql",
  416. "Psycopg specific cursor.closed attribute needed",
  417. )
  418. def test_cursor_contextmanager_closing(self):
  419. # There isn't a generic way to test that cursors are closed, but
  420. # psycopg offers us a way to check that by closed attribute.
  421. # So, run only on psycopg for that reason.
  422. with connection.cursor() as cursor:
  423. self.assertIsInstance(cursor, CursorWrapper)
  424. self.assertTrue(cursor.closed)
  425. # Unfortunately with sqlite3 the in-memory test database cannot be closed.
  426. @skipUnlessDBFeature("test_db_allows_multiple_connections")
  427. def test_is_usable_after_database_disconnects(self):
  428. """
  429. is_usable() doesn't crash when the database disconnects (#21553).
  430. """
  431. # Open a connection to the database.
  432. with connection.cursor():
  433. pass
  434. # Emulate a connection close by the database.
  435. connection._close()
  436. # Even then is_usable() should not raise an exception.
  437. try:
  438. self.assertFalse(connection.is_usable())
  439. finally:
  440. # Clean up the mess created by connection._close(). Since the
  441. # connection is already closed, this crashes on some backends.
  442. try:
  443. connection.close()
  444. except Exception:
  445. pass
  446. @override_settings(DEBUG=True)
  447. def test_queries(self):
  448. """
  449. Test the documented API of connection.queries.
  450. """
  451. sql = "SELECT 1" + connection.features.bare_select_suffix
  452. with connection.cursor() as cursor:
  453. reset_queries()
  454. cursor.execute(sql)
  455. self.assertEqual(1, len(connection.queries))
  456. self.assertIsInstance(connection.queries, list)
  457. self.assertIsInstance(connection.queries[0], dict)
  458. self.assertEqual(list(connection.queries[0]), ["sql", "time"])
  459. self.assertEqual(connection.queries[0]["sql"], sql)
  460. reset_queries()
  461. self.assertEqual(0, len(connection.queries))
  462. sql = "INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % (
  463. connection.introspection.identifier_converter("backends_square"),
  464. connection.ops.quote_name("root"),
  465. connection.ops.quote_name("square"),
  466. )
  467. with connection.cursor() as cursor:
  468. cursor.executemany(sql, [(1, 1), (2, 4)])
  469. self.assertEqual(1, len(connection.queries))
  470. self.assertIsInstance(connection.queries, list)
  471. self.assertIsInstance(connection.queries[0], dict)
  472. self.assertEqual(list(connection.queries[0]), ["sql", "time"])
  473. self.assertEqual(connection.queries[0]["sql"], "2 times: %s" % sql)
  474. # Unfortunately with sqlite3 the in-memory test database cannot be closed.
  475. @skipUnlessDBFeature("test_db_allows_multiple_connections")
  476. @override_settings(DEBUG=True)
  477. def test_queries_limit(self):
  478. """
  479. The backend doesn't store an unlimited number of queries (#12581).
  480. """
  481. old_queries_limit = BaseDatabaseWrapper.queries_limit
  482. BaseDatabaseWrapper.queries_limit = 3
  483. new_connection = connection.copy()
  484. # Initialize the connection and clear initialization statements.
  485. with new_connection.cursor():
  486. pass
  487. new_connection.queries_log.clear()
  488. try:
  489. with new_connection.cursor() as cursor:
  490. cursor.execute("SELECT 1" + new_connection.features.bare_select_suffix)
  491. cursor.execute("SELECT 2" + new_connection.features.bare_select_suffix)
  492. with warnings.catch_warnings(record=True) as w:
  493. self.assertEqual(2, len(new_connection.queries))
  494. self.assertEqual(0, len(w))
  495. with new_connection.cursor() as cursor:
  496. cursor.execute("SELECT 3" + new_connection.features.bare_select_suffix)
  497. cursor.execute("SELECT 4" + new_connection.features.bare_select_suffix)
  498. msg = (
  499. "Limit for query logging exceeded, only the last 3 queries will be "
  500. "returned."
  501. )
  502. with self.assertWarnsMessage(UserWarning, msg) as ctx:
  503. self.assertEqual(3, len(new_connection.queries))
  504. self.assertEqual(ctx.filename, __file__)
  505. finally:
  506. BaseDatabaseWrapper.queries_limit = old_queries_limit
  507. new_connection.close()
  508. @mock.patch("django.db.backends.utils.logger")
  509. @override_settings(DEBUG=True)
  510. def test_queries_logger(self, mocked_logger):
  511. sql = "SELECT 1" + connection.features.bare_select_suffix
  512. sql = connection.ops.format_debug_sql(sql)
  513. with connection.cursor() as cursor:
  514. cursor.execute(sql)
  515. params, kwargs = mocked_logger.debug.call_args
  516. self.assertIn("; alias=%s", params[0])
  517. self.assertEqual(params[2], sql)
  518. self.assertIsNone(params[3])
  519. self.assertEqual(params[4], connection.alias)
  520. self.assertEqual(
  521. list(kwargs["extra"]),
  522. ["duration", "sql", "params", "alias"],
  523. )
  524. self.assertEqual(tuple(kwargs["extra"].values()), params[1:])
  525. def test_queries_bare_where(self):
  526. sql = f"SELECT 1{connection.features.bare_select_suffix} WHERE 1=1"
  527. with connection.cursor() as cursor:
  528. cursor.execute(sql)
  529. self.assertEqual(cursor.fetchone(), (1,))
  530. def test_timezone_none_use_tz_false(self):
  531. connection.ensure_connection()
  532. with self.settings(TIME_ZONE=None, USE_TZ=False):
  533. connection.init_connection_state()
  534. # These tests aren't conditional because it would require differentiating
  535. # between MySQL+InnoDB and MySQL+MYISAM (something we currently can't do).
  536. class FkConstraintsTests(TransactionTestCase):
  537. available_apps = ["backends"]
  538. def setUp(self):
  539. # Create a Reporter.
  540. self.r = Reporter.objects.create(first_name="John", last_name="Smith")
  541. def test_integrity_checks_on_creation(self):
  542. """
  543. Try to create a model instance that violates a FK constraint. If it
  544. fails it should fail with IntegrityError.
  545. """
  546. a1 = Article(
  547. headline="This is a test",
  548. pub_date=datetime.datetime(2005, 7, 27),
  549. reporter_id=30,
  550. )
  551. try:
  552. a1.save()
  553. except IntegrityError:
  554. pass
  555. else:
  556. self.skipTest("This backend does not support integrity checks.")
  557. # Now that we know this backend supports integrity checks we make sure
  558. # constraints are also enforced for proxy Refs #17519
  559. a2 = Article(
  560. headline="This is another test",
  561. reporter=self.r,
  562. pub_date=datetime.datetime(2012, 8, 3),
  563. reporter_proxy_id=30,
  564. )
  565. with self.assertRaises(IntegrityError):
  566. a2.save()
  567. def test_integrity_checks_on_update(self):
  568. """
  569. Try to update a model instance introducing a FK constraint violation.
  570. If it fails it should fail with IntegrityError.
  571. """
  572. # Create an Article.
  573. Article.objects.create(
  574. headline="Test article",
  575. pub_date=datetime.datetime(2010, 9, 4),
  576. reporter=self.r,
  577. )
  578. # Retrieve it from the DB
  579. a1 = Article.objects.get(headline="Test article")
  580. a1.reporter_id = 30
  581. try:
  582. a1.save()
  583. except IntegrityError:
  584. pass
  585. else:
  586. self.skipTest("This backend does not support integrity checks.")
  587. # Now that we know this backend supports integrity checks we make sure
  588. # constraints are also enforced for proxy Refs #17519
  589. # Create another article
  590. r_proxy = ReporterProxy.objects.get(pk=self.r.pk)
  591. Article.objects.create(
  592. headline="Another article",
  593. pub_date=datetime.datetime(1988, 5, 15),
  594. reporter=self.r,
  595. reporter_proxy=r_proxy,
  596. )
  597. # Retrieve the second article from the DB
  598. a2 = Article.objects.get(headline="Another article")
  599. a2.reporter_proxy_id = 30
  600. with self.assertRaises(IntegrityError):
  601. a2.save()
  602. def test_disable_constraint_checks_manually(self):
  603. """
  604. When constraint checks are disabled, should be able to write bad data
  605. without IntegrityErrors.
  606. """
  607. with transaction.atomic():
  608. # Create an Article.
  609. Article.objects.create(
  610. headline="Test article",
  611. pub_date=datetime.datetime(2010, 9, 4),
  612. reporter=self.r,
  613. )
  614. # Retrieve it from the DB
  615. a = Article.objects.get(headline="Test article")
  616. a.reporter_id = 30
  617. try:
  618. connection.disable_constraint_checking()
  619. a.save()
  620. connection.enable_constraint_checking()
  621. except IntegrityError:
  622. self.fail("IntegrityError should not have occurred.")
  623. transaction.set_rollback(True)
  624. def test_disable_constraint_checks_context_manager(self):
  625. """
  626. When constraint checks are disabled (using context manager), should be
  627. able to write bad data without IntegrityErrors.
  628. """
  629. with transaction.atomic():
  630. # Create an Article.
  631. Article.objects.create(
  632. headline="Test article",
  633. pub_date=datetime.datetime(2010, 9, 4),
  634. reporter=self.r,
  635. )
  636. # Retrieve it from the DB
  637. a = Article.objects.get(headline="Test article")
  638. a.reporter_id = 30
  639. try:
  640. with connection.constraint_checks_disabled():
  641. a.save()
  642. except IntegrityError:
  643. self.fail("IntegrityError should not have occurred.")
  644. transaction.set_rollback(True)
  645. def test_check_constraints(self):
  646. """
  647. Constraint checks should raise an IntegrityError when bad data is in the DB.
  648. """
  649. with transaction.atomic():
  650. # Create an Article.
  651. Article.objects.create(
  652. headline="Test article",
  653. pub_date=datetime.datetime(2010, 9, 4),
  654. reporter=self.r,
  655. )
  656. # Retrieve it from the DB
  657. a = Article.objects.get(headline="Test article")
  658. a.reporter_id = 30
  659. with connection.constraint_checks_disabled():
  660. a.save()
  661. try:
  662. connection.check_constraints(table_names=[Article._meta.db_table])
  663. except IntegrityError:
  664. pass
  665. else:
  666. self.skipTest("This backend does not support integrity checks.")
  667. transaction.set_rollback(True)
  668. def test_check_constraints_sql_keywords(self):
  669. with transaction.atomic():
  670. obj = SQLKeywordsModel.objects.create(reporter=self.r)
  671. obj.refresh_from_db()
  672. obj.reporter_id = 30
  673. with connection.constraint_checks_disabled():
  674. obj.save()
  675. try:
  676. connection.check_constraints(table_names=["order"])
  677. except IntegrityError:
  678. pass
  679. else:
  680. self.skipTest("This backend does not support integrity checks.")
  681. transaction.set_rollback(True)
  682. class ThreadTests(TransactionTestCase):
  683. available_apps = ["backends"]
  684. def test_default_connection_thread_local(self):
  685. """
  686. The default connection (i.e. django.db.connection) is different for
  687. each thread (#17258).
  688. """
  689. # Map connections by id because connections with identical aliases
  690. # have the same hash.
  691. connections_dict = {}
  692. with connection.cursor():
  693. pass
  694. connections_dict[id(connection)] = connection
  695. def runner():
  696. # Passing django.db.connection between threads doesn't work while
  697. # connections[DEFAULT_DB_ALIAS] does.
  698. from django.db import connections
  699. connection = connections[DEFAULT_DB_ALIAS]
  700. # Allow thread sharing so the connection can be closed by the
  701. # main thread.
  702. connection.inc_thread_sharing()
  703. with connection.cursor():
  704. pass
  705. connections_dict[id(connection)] = connection
  706. try:
  707. for x in range(2):
  708. t = threading.Thread(target=runner)
  709. t.start()
  710. t.join()
  711. # Each created connection got different inner connection.
  712. self.assertEqual(
  713. len({conn.connection for conn in connections_dict.values()}), 3
  714. )
  715. finally:
  716. # Finish by closing the connections opened by the other threads
  717. # (the connection opened in the main thread will automatically be
  718. # closed on teardown).
  719. for conn in connections_dict.values():
  720. if conn is not connection and conn.allow_thread_sharing:
  721. conn.validate_thread_sharing()
  722. conn._close()
  723. conn.dec_thread_sharing()
  724. def test_connections_thread_local(self):
  725. """
  726. The connections are different for each thread (#17258).
  727. """
  728. # Map connections by id because connections with identical aliases
  729. # have the same hash.
  730. connections_dict = {}
  731. for conn in connections.all():
  732. connections_dict[id(conn)] = conn
  733. def runner():
  734. from django.db import connections
  735. for conn in connections.all():
  736. # Allow thread sharing so the connection can be closed by the
  737. # main thread.
  738. conn.inc_thread_sharing()
  739. connections_dict[id(conn)] = conn
  740. try:
  741. num_new_threads = 2
  742. for x in range(num_new_threads):
  743. t = threading.Thread(target=runner)
  744. t.start()
  745. t.join()
  746. self.assertEqual(
  747. len(connections_dict),
  748. len(connections.all()) * (num_new_threads + 1),
  749. )
  750. finally:
  751. # Finish by closing the connections opened by the other threads
  752. # (the connection opened in the main thread will automatically be
  753. # closed on teardown).
  754. for conn in connections_dict.values():
  755. if conn is not connection and conn.allow_thread_sharing:
  756. conn.close()
  757. conn.dec_thread_sharing()
  758. def test_pass_connection_between_threads(self):
  759. """
  760. A connection can be passed from one thread to the other (#17258).
  761. """
  762. Person.objects.create(first_name="John", last_name="Doe")
  763. def do_thread():
  764. def runner(main_thread_connection):
  765. from django.db import connections
  766. connections["default"] = main_thread_connection
  767. try:
  768. Person.objects.get(first_name="John", last_name="Doe")
  769. except Exception as e:
  770. exceptions.append(e)
  771. t = threading.Thread(target=runner, args=[connections["default"]])
  772. t.start()
  773. t.join()
  774. # Without touching thread sharing, which should be False by default.
  775. exceptions = []
  776. do_thread()
  777. # Forbidden!
  778. self.assertIsInstance(exceptions[0], DatabaseError)
  779. connections["default"].close()
  780. # After calling inc_thread_sharing() on the connection.
  781. connections["default"].inc_thread_sharing()
  782. try:
  783. exceptions = []
  784. do_thread()
  785. # All good
  786. self.assertEqual(exceptions, [])
  787. finally:
  788. connections["default"].dec_thread_sharing()
  789. def test_closing_non_shared_connections(self):
  790. """
  791. A connection that is not explicitly shareable cannot be closed by
  792. another thread (#17258).
  793. """
  794. # First, without explicitly enabling the connection for sharing.
  795. exceptions = set()
  796. def runner1():
  797. def runner2(other_thread_connection):
  798. try:
  799. other_thread_connection.close()
  800. except DatabaseError as e:
  801. exceptions.add(e)
  802. t2 = threading.Thread(target=runner2, args=[connections["default"]])
  803. t2.start()
  804. t2.join()
  805. t1 = threading.Thread(target=runner1)
  806. t1.start()
  807. t1.join()
  808. # The exception was raised
  809. self.assertEqual(len(exceptions), 1)
  810. # Then, with explicitly enabling the connection for sharing.
  811. exceptions = set()
  812. def runner1():
  813. def runner2(other_thread_connection):
  814. try:
  815. other_thread_connection.close()
  816. except DatabaseError as e:
  817. exceptions.add(e)
  818. # Enable thread sharing
  819. connections["default"].inc_thread_sharing()
  820. try:
  821. t2 = threading.Thread(target=runner2, args=[connections["default"]])
  822. t2.start()
  823. t2.join()
  824. finally:
  825. connections["default"].dec_thread_sharing()
  826. t1 = threading.Thread(target=runner1)
  827. t1.start()
  828. t1.join()
  829. # No exception was raised
  830. self.assertEqual(len(exceptions), 0)
  831. def test_thread_sharing_count(self):
  832. self.assertIs(connection.allow_thread_sharing, False)
  833. connection.inc_thread_sharing()
  834. self.assertIs(connection.allow_thread_sharing, True)
  835. connection.inc_thread_sharing()
  836. self.assertIs(connection.allow_thread_sharing, True)
  837. connection.dec_thread_sharing()
  838. self.assertIs(connection.allow_thread_sharing, True)
  839. connection.dec_thread_sharing()
  840. self.assertIs(connection.allow_thread_sharing, False)
  841. msg = "Cannot decrement the thread sharing count below zero."
  842. with self.assertRaisesMessage(RuntimeError, msg):
  843. connection.dec_thread_sharing()
  844. class MySQLPKZeroTests(TestCase):
  845. """
  846. Zero as id for AutoField should raise exception in MySQL, because MySQL
  847. does not allow zero for autoincrement primary key if the
  848. NO_AUTO_VALUE_ON_ZERO SQL mode is not enabled.
  849. """
  850. @skipIfDBFeature("allows_auto_pk_0")
  851. def test_zero_as_autoval(self):
  852. with self.assertRaises(ValueError):
  853. Square.objects.create(id=0, root=0, square=1)
  854. class DBConstraintTestCase(TestCase):
  855. def test_can_reference_existent(self):
  856. obj = Object.objects.create()
  857. ref = ObjectReference.objects.create(obj=obj)
  858. self.assertEqual(ref.obj, obj)
  859. ref = ObjectReference.objects.get(obj=obj)
  860. self.assertEqual(ref.obj, obj)
  861. def test_can_reference_non_existent(self):
  862. self.assertFalse(Object.objects.filter(id=12345).exists())
  863. ref = ObjectReference.objects.create(obj_id=12345)
  864. ref_new = ObjectReference.objects.get(obj_id=12345)
  865. self.assertEqual(ref, ref_new)
  866. with self.assertRaises(Object.DoesNotExist):
  867. ref.obj
  868. def test_many_to_many(self):
  869. obj = Object.objects.create()
  870. obj.related_objects.create()
  871. self.assertEqual(Object.objects.count(), 2)
  872. self.assertEqual(obj.related_objects.count(), 1)
  873. intermediary_model = Object._meta.get_field(
  874. "related_objects"
  875. ).remote_field.through
  876. intermediary_model.objects.create(from_object_id=obj.id, to_object_id=12345)
  877. self.assertEqual(obj.related_objects.count(), 1)
  878. self.assertEqual(intermediary_model.objects.count(), 2)