tests.py 37 KB

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