Debian Codegraph @

tests/backends/oracle/tests.py

raw
1 import copy
2 import unittest
3 from unittest import mock
4
5 from django.core.exceptions import ImproperlyConfigured
6 from django.db import DatabaseError, NotSupportedError, ProgrammingError, connection
7 from django.db.models import BooleanField
8 from django.test import TestCase, TransactionTestCase
9
10 from ..models import Square, VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
11
12 try:
13 from django.db.backends.oracle.oracledb_any import is_oracledb
14 except ImportError:
15 is_oracledb = False
16
17
18 def no_pool_connection(alias=None):
19 new_connection = connection.copy(alias)
20 new_connection.settings_dict = copy.deepcopy(connection.settings_dict)
21 # Ensure that the second connection circumvents the pool, this is kind
22 # of a hack, but we cannot easily change the pool connections.
23 new_connection.settings_dict["OPTIONS"]["pool"] = False
24 return new_connection
25
26
27 @unittest.skipUnless(connection.vendor == "oracle", "Oracle tests")
28 class Tests(TestCase):
29 def test_quote_name(self):
30 """'%' chars are escaped for query execution."""
31 name = '"SOME%NAME"'
32 quoted_name = connection.ops.quote_name(name)
33 self.assertEqual(quoted_name % (), name)
34
35 def test_quote_name_db_table(self):
36 model = VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
37 db_table = model._meta.db_table.upper()
38 self.assertEqual(
39 f'"{db_table}"',
40 connection.ops.quote_name(
41 "backends_verylongmodelnamezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
42 ),
43 )
44
45 def test_dbms_session(self):
46 """A stored procedure can be called through a cursor wrapper."""
47 with connection.cursor() as cursor:
48 cursor.callproc("DBMS_SESSION.SET_IDENTIFIER", ["_django_testing!"])
49
50 def test_cursor_var(self):
51 """Cursor variables can be passed as query parameters."""
52 with connection.cursor() as cursor:
53 var = cursor.var(str)
54 cursor.execute("BEGIN %s := 'X'; END; ", [var])
55 self.assertEqual(var.getvalue(), "X")
56
57 def test_order_of_nls_parameters(self):
58 """
59 An 'almost right' datetime works with configured NLS parameters
60 (#18465).
61 """
62 suffix = connection.features.bare_select_suffix
63 with connection.cursor() as cursor:
64 query = f"SELECT 1{suffix} WHERE '1936-12-29 00:00' < SYSDATE"
65 # The query succeeds without errors - pre #18465 this
66 # wasn't the case.
67 cursor.execute(query)
68 self.assertEqual(cursor.fetchone()[0], 1)
69
70 def test_boolean_constraints(self):
71 """Boolean fields have check constraints on their values."""
72 for field in (BooleanField(), BooleanField(null=True)):
73 with self.subTest(field=field):
74 field.set_attributes_from_name("is_nice")
75 self.assertIn('"IS_NICE" IN (0,1)', field.db_check(connection))
76
77 @mock.patch.object(
78 connection,
79 "get_database_version",
80 return_value=(18, 1),
81 )
82 def test_check_database_version_supported(self, mocked_get_database_version):
83 msg = "Oracle 19 or later is required (found 18.1)."
84 with self.assertRaisesMessage(NotSupportedError, msg):
85 connection.check_database_version_supported()
86 self.assertTrue(mocked_get_database_version.called)
87
88 @unittest.skipUnless(is_oracledb, "Pool specific tests")
89 def test_pool_set_to_true(self):
90 new_connection = no_pool_connection(alias="default_pool")
91 new_connection.settings_dict["OPTIONS"]["pool"] = True
92 try:
93 self.assertIsNotNone(new_connection.pool)
94 finally:
95 new_connection.close_pool()
96
97 @unittest.skipUnless(is_oracledb, "Pool specific tests")
98 def test_pool_reuse(self):
99 new_connection = no_pool_connection(alias="default_pool")
100 new_connection.settings_dict["OPTIONS"]["pool"] = {
101 "min": 0,
102 "max": 2,
103 }
104 self.assertIsNotNone(new_connection.pool)
105
106 connections = []
107
108 def get_connection():
109 # copy() reuses the existing alias and as such the same pool.
110 conn = new_connection.copy()
111 conn.connect()
112 connections.append(conn)
113 return conn
114
115 try:
116 connection_1 = get_connection() # First connection.
117 get_connection() # Get the second connection.
118 sql = "select sys_context('userenv', 'sid') from dual"
119 sids = [conn.cursor().execute(sql).fetchone()[0] for conn in connections]
120 connection_1.close() # Release back to the pool.
121 connection_3 = get_connection()
122 sid = connection_3.cursor().execute(sql).fetchone()[0]
123 # Reuses the first connection as it is available.
124 self.assertEqual(sid, sids[0])
125 finally:
126 # Release all connections back to the pool.
127 for conn in connections:
128 conn.close()
129 new_connection.close_pool()
130
131 @unittest.skipUnless(is_oracledb, "Pool specific tests")
132 def test_cannot_open_new_connection_in_atomic_block(self):
133 new_connection = no_pool_connection(alias="default_pool")
134 new_connection.settings_dict["OPTIONS"]["pool"] = True
135 msg = "Cannot open a new connection in an atomic block."
136 new_connection.in_atomic_block = True
137 new_connection.closed_in_transaction = True
138 with self.assertRaisesMessage(ProgrammingError, msg):
139 new_connection.ensure_connection()
140
141 @unittest.skipUnless(is_oracledb, "Pool specific tests")
142 def test_pooling_not_support_persistent_connections(self):
143 new_connection = no_pool_connection(alias="default_pool")
144 new_connection.settings_dict["OPTIONS"]["pool"] = True
145 new_connection.settings_dict["CONN_MAX_AGE"] = 10
146 msg = "Pooling doesn't support persistent connections."
147 with self.assertRaisesMessage(ImproperlyConfigured, msg):
148 new_connection.pool
149
150 @unittest.skipIf(is_oracledb, "cx_oracle specific tests")
151 def test_cx_Oracle_not_support_pooling(self):
152 new_connection = no_pool_connection()
153 new_connection.settings_dict["OPTIONS"]["pool"] = True
154 msg = "Pooling isn't supported by cx_Oracle. Use python-oracledb instead."
155 with self.assertRaisesMessage(ImproperlyConfigured, msg):
156 new_connection.connect()
157
158
159 @unittest.skipUnless(connection.vendor == "oracle", "Oracle tests")
160 class TransactionalTests(TransactionTestCase):
161 available_apps = ["backends"]
162
163 def test_hidden_no_data_found_exception(self):
164 # "ORA-1403: no data found" exception is hidden by Oracle OCI library
165 # when an INSERT statement is used with a RETURNING clause (see #28859).
166 with connection.cursor() as cursor:
167 # Create trigger that raises "ORA-1403: no data found".
168 cursor.execute("""
169 CREATE OR REPLACE TRIGGER "TRG_NO_DATA_FOUND"
170 AFTER INSERT ON "BACKENDS_SQUARE"
171 FOR EACH ROW
172 BEGIN
173 RAISE NO_DATA_FOUND;
174 END;
175 """)
176 try:
177 with self.assertRaisesMessage(
178 DatabaseError,
179 (
180 'The database did not return a new row id. Probably "ORA-1403: no '
181 'data found" was raised internally but was hidden by the Oracle '
182 "OCI library (see https://code.djangoproject.com/ticket/28859)."
183 ),
184 ):
185 Square.objects.create(root=2, square=4)
186 finally:
187 with connection.cursor() as cursor:
188 cursor.execute('DROP TRIGGER "TRG_NO_DATA_FOUND"')
189
190 def test_password_with_at_sign(self):
191 from django.db.backends.oracle.base import Database
192
193 old_password = connection.settings_dict["PASSWORD"]
194 connection.settings_dict["PASSWORD"] = "p@ssword"
195 try:
196 self.assertIn(
197 '/"p@ssword"@',
198 connection.client.connect_string(connection.settings_dict),
199 )
200 with self.assertRaises(Database.DatabaseError) as context:
201 connection.connect()
202 # Database exception: "ORA-01017: invalid username/password" is
203 # expected.
204 self.assertIn("ORA-01017", context.exception.args[0].message)
205 finally:
206 connection.settings_dict["PASSWORD"] = old_password