Debian Codegraph @

tests/backends/postgresql/test_compilation.py

raw
1 import unittest
2 from datetime import date
3
4 from django.db import connection
5 from django.db.models.expressions import RawSQL
6 from django.db.utils import DataError
7 from django.test import TestCase
8
9 from ..models import Article, Reporter, Square
10
11
12 @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL tests")
13 class BulkCreateUnnestTests(TestCase):
14 def test_single_object(self):
15 with self.assertNumQueries(1) as ctx:
16 Square.objects.bulk_create([Square(root=2, square=4)])
17 self.assertNotIn("UNNEST", ctx[0]["sql"])
18
19 def test_non_literal(self):
20 with self.assertNumQueries(1) as ctx:
21 Square.objects.bulk_create(
22 [Square(root=2, square=RawSQL("%s", (4,))), Square(root=3, square=9)]
23 )
24 self.assertNotIn("UNNEST", ctx[0]["sql"])
25
26 def test_unnest_eligible(self):
27 with self.assertNumQueries(1) as ctx:
28 Square.objects.bulk_create(
29 [Square(root=2, square=4), Square(root=3, square=9)]
30 )
31 self.assertIn("UNNEST", ctx[0]["sql"])
32
33 def test_unnest_eligible_foreign_keys(self):
34 reporter = Reporter.objects.create()
35 with self.assertNumQueries(1) as ctx:
36 articles = Article.objects.bulk_create(
37 [
38 Article(pub_date=date.today(), reporter=reporter),
39 Article(pub_date=date.today(), reporter=reporter),
40 ]
41 )
42 self.assertIn("UNNEST", ctx[0]["sql"])
43 self.assertEqual(
44 [article.reporter for article in articles], [reporter, reporter]
45 )
46
47 def test_parametrized_db_type(self):
48 with self.assertRaises(DataError):
49 Reporter.objects.bulk_create(
50 [
51 Reporter(),
52 Reporter(first_name="a" * 31),
53 ]
54 )