Debian Codegraph @

Lib/test/test_sqlite3/test_dbapi.py

raw
1 # pysqlite2/test/dbapi.py: tests for DB-API compliance
2 #
3 # Copyright (C) 2004-2010 Gerhard Häring <[email protected]>
4 #
5 # This file is part of pysqlite.
6 #
7 # This software is provided 'as-is', without any express or implied
8 # warranty. In no event will the authors be held liable for any damages
9 # arising from the use of this software.
10 #
11 # Permission is granted to anyone to use this software for any purpose,
12 # including commercial applications, and to alter it and redistribute it
13 # freely, subject to the following restrictions:
14 #
15 # 1. The origin of this software must not be misrepresented; you must not
16 # claim that you wrote the original software. If you use this software
17 # in a product, an acknowledgment in the product documentation would be
18 # appreciated but is not required.
19 # 2. Altered source versions must be plainly marked as such, and must not be
20 # misrepresented as being the original software.
21 # 3. This notice may not be removed or altered from any source distribution.
22
23 import contextlib
24 import functools
25 import os
26 import sqlite3 as sqlite
27 import subprocess
28 import sys
29 import threading
30 import unittest
31 import urllib.parse
32 import warnings
33
34 from test.support import (
35 SHORT_TIMEOUT, check_disallow_instantiation, requires_subprocess
36 )
37 from test.support import gc_collect
38 from test.support import threading_helper, import_helper
39 from os import SEEK_SET, SEEK_CUR, SEEK_END
40 from test.support.os_helper import TESTFN, TESTFN_UNDECODABLE, unlink, temp_dir, FakePath
41
42 from .util import memory_database, cx_limit
43 from .util import MemoryDatabaseMixin
44
45
46 class ModuleTests(unittest.TestCase):
47 def test_api_level(self):
48 self.assertEqual(sqlite.apilevel, "2.0",
49 "apilevel is %s, should be 2.0" % sqlite.apilevel)
50
51 def test_deprecated_version(self):
52 msg = "deprecated and will be removed in Python 3.14"
53 for attr in "version", "version_info":
54 with self.subTest(attr=attr):
55 with self.assertWarnsRegex(DeprecationWarning, msg) as cm:
56 getattr(sqlite, attr)
57 self.assertEqual(cm.filename, __file__)
58 with self.assertWarnsRegex(DeprecationWarning, msg) as cm:
59 getattr(sqlite.dbapi2, attr)
60 self.assertEqual(cm.filename, __file__)
61
62 def test_thread_safety(self):
63 self.assertIn(sqlite.threadsafety, {0, 1, 3},
64 "threadsafety is %d, should be 0, 1 or 3" %
65 sqlite.threadsafety)
66
67 def test_param_style(self):
68 self.assertEqual(sqlite.paramstyle, "qmark",
69 "paramstyle is '%s', should be 'qmark'" %
70 sqlite.paramstyle)
71
72 def test_warning(self):
73 self.assertTrue(issubclass(sqlite.Warning, Exception),
74 "Warning is not a subclass of Exception")
75
76 def test_error(self):
77 self.assertTrue(issubclass(sqlite.Error, Exception),
78 "Error is not a subclass of Exception")
79
80 def test_interface_error(self):
81 self.assertTrue(issubclass(sqlite.InterfaceError, sqlite.Error),
82 "InterfaceError is not a subclass of Error")
83
84 def test_database_error(self):
85 self.assertTrue(issubclass(sqlite.DatabaseError, sqlite.Error),
86 "DatabaseError is not a subclass of Error")
87
88 def test_data_error(self):
89 self.assertTrue(issubclass(sqlite.DataError, sqlite.DatabaseError),
90 "DataError is not a subclass of DatabaseError")
91
92 def test_operational_error(self):
93 self.assertTrue(issubclass(sqlite.OperationalError, sqlite.DatabaseError),
94 "OperationalError is not a subclass of DatabaseError")
95
96 def test_integrity_error(self):
97 self.assertTrue(issubclass(sqlite.IntegrityError, sqlite.DatabaseError),
98 "IntegrityError is not a subclass of DatabaseError")
99
100 def test_internal_error(self):
101 self.assertTrue(issubclass(sqlite.InternalError, sqlite.DatabaseError),
102 "InternalError is not a subclass of DatabaseError")
103
104 def test_programming_error(self):
105 self.assertTrue(issubclass(sqlite.ProgrammingError, sqlite.DatabaseError),
106 "ProgrammingError is not a subclass of DatabaseError")
107
108 def test_not_supported_error(self):
109 self.assertTrue(issubclass(sqlite.NotSupportedError,
110 sqlite.DatabaseError),
111 "NotSupportedError is not a subclass of DatabaseError")
112
113 def test_module_constants(self):
114 consts = [
115 "SQLITE_ABORT",
116 "SQLITE_ALTER_TABLE",
117 "SQLITE_ANALYZE",
118 "SQLITE_ATTACH",
119 "SQLITE_AUTH",
120 "SQLITE_BUSY",
121 "SQLITE_CANTOPEN",
122 "SQLITE_CONSTRAINT",
123 "SQLITE_CORRUPT",
124 "SQLITE_CREATE_INDEX",
125 "SQLITE_CREATE_TABLE",
126 "SQLITE_CREATE_TEMP_INDEX",
127 "SQLITE_CREATE_TEMP_TABLE",
128 "SQLITE_CREATE_TEMP_TRIGGER",
129 "SQLITE_CREATE_TEMP_VIEW",
130 "SQLITE_CREATE_TRIGGER",
131 "SQLITE_CREATE_VIEW",
132 "SQLITE_CREATE_VTABLE",
133 "SQLITE_DELETE",
134 "SQLITE_DENY",
135 "SQLITE_DETACH",
136 "SQLITE_DONE",
137 "SQLITE_DROP_INDEX",
138 "SQLITE_DROP_TABLE",
139 "SQLITE_DROP_TEMP_INDEX",
140 "SQLITE_DROP_TEMP_TABLE",
141 "SQLITE_DROP_TEMP_TRIGGER",
142 "SQLITE_DROP_TEMP_VIEW",
143 "SQLITE_DROP_TRIGGER",
144 "SQLITE_DROP_VIEW",
145 "SQLITE_DROP_VTABLE",
146 "SQLITE_EMPTY",
147 "SQLITE_ERROR",
148 "SQLITE_FORMAT",
149 "SQLITE_FULL",
150 "SQLITE_FUNCTION",
151 "SQLITE_IGNORE",
152 "SQLITE_INSERT",
153 "SQLITE_INTERNAL",
154 "SQLITE_INTERRUPT",
155 "SQLITE_IOERR",
156 "SQLITE_LIMIT_WORKER_THREADS",
157 "SQLITE_LOCKED",
158 "SQLITE_MISMATCH",
159 "SQLITE_MISUSE",
160 "SQLITE_NOLFS",
161 "SQLITE_NOMEM",
162 "SQLITE_NOTADB",
163 "SQLITE_NOTFOUND",
164 "SQLITE_NOTICE",
165 "SQLITE_OK",
166 "SQLITE_PERM",
167 "SQLITE_PRAGMA",
168 "SQLITE_PROTOCOL",
169 "SQLITE_RANGE",
170 "SQLITE_READ",
171 "SQLITE_READONLY",
172 "SQLITE_RECURSIVE",
173 "SQLITE_REINDEX",
174 "SQLITE_ROW",
175 "SQLITE_SAVEPOINT",
176 "SQLITE_SCHEMA",
177 "SQLITE_SELECT",
178 "SQLITE_TOOBIG",
179 "SQLITE_TRANSACTION",
180 "SQLITE_UPDATE",
181 "SQLITE_WARNING",
182 # Run-time limit categories
183 "SQLITE_LIMIT_LENGTH",
184 "SQLITE_LIMIT_SQL_LENGTH",
185 "SQLITE_LIMIT_COLUMN",
186 "SQLITE_LIMIT_EXPR_DEPTH",
187 "SQLITE_LIMIT_COMPOUND_SELECT",
188 "SQLITE_LIMIT_VDBE_OP",
189 "SQLITE_LIMIT_FUNCTION_ARG",
190 "SQLITE_LIMIT_ATTACHED",
191 "SQLITE_LIMIT_LIKE_PATTERN_LENGTH",
192 "SQLITE_LIMIT_VARIABLE_NUMBER",
193 "SQLITE_LIMIT_TRIGGER_DEPTH",
194 ]
195 consts += ["PARSE_DECLTYPES", "PARSE_COLNAMES"]
196 # Extended result codes
197 consts += [
198 "SQLITE_ABORT_ROLLBACK",
199 "SQLITE_AUTH_USER",
200 "SQLITE_BUSY_RECOVERY",
201 "SQLITE_BUSY_SNAPSHOT",
202 "SQLITE_CANTOPEN_CONVPATH",
203 "SQLITE_CANTOPEN_FULLPATH",
204 "SQLITE_CANTOPEN_ISDIR",
205 "SQLITE_CANTOPEN_NOTEMPDIR",
206 "SQLITE_CONSTRAINT_CHECK",
207 "SQLITE_CONSTRAINT_COMMITHOOK",
208 "SQLITE_CONSTRAINT_FOREIGNKEY",
209 "SQLITE_CONSTRAINT_FUNCTION",
210 "SQLITE_CONSTRAINT_NOTNULL",
211 "SQLITE_CONSTRAINT_PRIMARYKEY",
212 "SQLITE_CONSTRAINT_ROWID",
213 "SQLITE_CONSTRAINT_TRIGGER",
214 "SQLITE_CONSTRAINT_UNIQUE",
215 "SQLITE_CONSTRAINT_VTAB",
216 "SQLITE_CORRUPT_VTAB",
217 "SQLITE_IOERR_ACCESS",
218 "SQLITE_IOERR_AUTH",
219 "SQLITE_IOERR_BLOCKED",
220 "SQLITE_IOERR_CHECKRESERVEDLOCK",
221 "SQLITE_IOERR_CLOSE",
222 "SQLITE_IOERR_CONVPATH",
223 "SQLITE_IOERR_DELETE",
224 "SQLITE_IOERR_DELETE_NOENT",
225 "SQLITE_IOERR_DIR_CLOSE",
226 "SQLITE_IOERR_DIR_FSYNC",
227 "SQLITE_IOERR_FSTAT",
228 "SQLITE_IOERR_FSYNC",
229 "SQLITE_IOERR_GETTEMPPATH",
230 "SQLITE_IOERR_LOCK",
231 "SQLITE_IOERR_MMAP",
232 "SQLITE_IOERR_NOMEM",
233 "SQLITE_IOERR_RDLOCK",
234 "SQLITE_IOERR_READ",
235 "SQLITE_IOERR_SEEK",
236 "SQLITE_IOERR_SHMLOCK",
237 "SQLITE_IOERR_SHMMAP",
238 "SQLITE_IOERR_SHMOPEN",
239 "SQLITE_IOERR_SHMSIZE",
240 "SQLITE_IOERR_SHORT_READ",
241 "SQLITE_IOERR_TRUNCATE",
242 "SQLITE_IOERR_UNLOCK",
243 "SQLITE_IOERR_VNODE",
244 "SQLITE_IOERR_WRITE",
245 "SQLITE_LOCKED_SHAREDCACHE",
246 "SQLITE_NOTICE_RECOVER_ROLLBACK",
247 "SQLITE_NOTICE_RECOVER_WAL",
248 "SQLITE_OK_LOAD_PERMANENTLY",
249 "SQLITE_READONLY_CANTLOCK",
250 "SQLITE_READONLY_DBMOVED",
251 "SQLITE_READONLY_RECOVERY",
252 "SQLITE_READONLY_ROLLBACK",
253 "SQLITE_WARNING_AUTOINDEX",
254 ]
255 if sqlite.sqlite_version_info >= (3, 21, 0):
256 consts += [
257 "SQLITE_IOERR_BEGIN_ATOMIC",
258 "SQLITE_IOERR_COMMIT_ATOMIC",
259 "SQLITE_IOERR_ROLLBACK_ATOMIC",
260 ]
261 if sqlite.sqlite_version_info >= (3, 22, 0):
262 consts += [
263 "SQLITE_ERROR_MISSING_COLLSEQ",
264 "SQLITE_ERROR_RETRY",
265 "SQLITE_READONLY_CANTINIT",
266 "SQLITE_READONLY_DIRECTORY",
267 ]
268 if sqlite.sqlite_version_info >= (3, 24, 0):
269 consts += ["SQLITE_CORRUPT_SEQUENCE", "SQLITE_LOCKED_VTAB"]
270 if sqlite.sqlite_version_info >= (3, 25, 0):
271 consts += ["SQLITE_CANTOPEN_DIRTYWAL", "SQLITE_ERROR_SNAPSHOT"]
272 if sqlite.sqlite_version_info >= (3, 31, 0):
273 consts += [
274 "SQLITE_CANTOPEN_SYMLINK",
275 "SQLITE_CONSTRAINT_PINNED",
276 "SQLITE_OK_SYMLINK",
277 ]
278 if sqlite.sqlite_version_info >= (3, 32, 0):
279 consts += [
280 "SQLITE_BUSY_TIMEOUT",
281 "SQLITE_CORRUPT_INDEX",
282 "SQLITE_IOERR_DATA",
283 ]
284 if sqlite.sqlite_version_info >= (3, 34, 0):
285 consts.append("SQLITE_IOERR_CORRUPTFS")
286 for const in consts:
287 with self.subTest(const=const):
288 self.assertTrue(hasattr(sqlite, const))
289
290 def test_error_code_on_exception(self):
291 err_msg = "unable to open database file"
292 if sys.platform.startswith("win"):
293 err_code = sqlite.SQLITE_CANTOPEN_ISDIR
294 else:
295 err_code = sqlite.SQLITE_CANTOPEN
296
297 with temp_dir() as db:
298 with self.assertRaisesRegex(sqlite.Error, err_msg) as cm:
299 sqlite.connect(db)
300 e = cm.exception
301 self.assertEqual(e.sqlite_errorcode, err_code)
302 self.assertTrue(e.sqlite_errorname.startswith("SQLITE_CANTOPEN"))
303
304 def test_extended_error_code_on_exception(self):
305 with memory_database() as con:
306 with con:
307 con.execute("create table t(t integer check(t > 0))")
308 errmsg = "constraint failed"
309 with self.assertRaisesRegex(sqlite.IntegrityError, errmsg) as cm:
310 con.execute("insert into t values(-1)")
311 exc = cm.exception
312 self.assertEqual(exc.sqlite_errorcode,
313 sqlite.SQLITE_CONSTRAINT_CHECK)
314 self.assertEqual(exc.sqlite_errorname, "SQLITE_CONSTRAINT_CHECK")
315
316 def test_disallow_instantiation(self):
317 with memory_database() as cx:
318 check_disallow_instantiation(self, type(cx("select 1")))
319 check_disallow_instantiation(self, sqlite.Blob)
320
321 def test_complete_statement(self):
322 self.assertFalse(sqlite.complete_statement("select t"))
323 self.assertTrue(sqlite.complete_statement("create table t(t);"))
324
325
326 class ConnectionTests(unittest.TestCase):
327
328 def setUp(self):
329 self.cx = sqlite.connect(":memory:")
330 cu = self.cx.cursor()
331 cu.execute("create table test(id integer primary key, name text)")
332 cu.execute("insert into test(name) values (?)", ("foo",))
333 cu.close()
334
335 def tearDown(self):
336 self.cx.close()
337
338 def test_commit(self):
339 self.cx.commit()
340
341 def test_commit_after_no_changes(self):
342 """
343 A commit should also work when no changes were made to the database.
344 """
345 self.cx.commit()
346 self.cx.commit()
347
348 def test_rollback(self):
349 self.cx.rollback()
350
351 def test_rollback_after_no_changes(self):
352 """
353 A rollback should also work when no changes were made to the database.
354 """
355 self.cx.rollback()
356 self.cx.rollback()
357
358 def test_cursor(self):
359 cu = self.cx.cursor()
360
361 def test_failed_open(self):
362 YOU_CANNOT_OPEN_THIS = "/foo/bar/bla/23534/mydb.db"
363 with self.assertRaises(sqlite.OperationalError):
364 sqlite.connect(YOU_CANNOT_OPEN_THIS)
365
366 def test_close(self):
367 self.cx.close()
368
369 def test_use_after_close(self):
370 sql = "select 1"
371 cu = self.cx.cursor()
372 res = cu.execute(sql)
373 self.cx.close()
374 self.assertRaises(sqlite.ProgrammingError, res.fetchall)
375 self.assertRaises(sqlite.ProgrammingError, cu.execute, sql)
376 self.assertRaises(sqlite.ProgrammingError, cu.executemany, sql, [])
377 self.assertRaises(sqlite.ProgrammingError, cu.executescript, sql)
378 self.assertRaises(sqlite.ProgrammingError, self.cx.execute, sql)
379 self.assertRaises(sqlite.ProgrammingError,
380 self.cx.executemany, sql, [])
381 self.assertRaises(sqlite.ProgrammingError, self.cx.executescript, sql)
382 self.assertRaises(sqlite.ProgrammingError,
383 self.cx.create_function, "t", 1, lambda x: x)
384 self.assertRaises(sqlite.ProgrammingError, self.cx.cursor)
385 with self.assertRaises(sqlite.ProgrammingError):
386 with self.cx:
387 pass
388
389 def test_exceptions(self):
390 # Optional DB-API extension.
391 self.assertEqual(self.cx.Warning, sqlite.Warning)
392 self.assertEqual(self.cx.Error, sqlite.Error)
393 self.assertEqual(self.cx.InterfaceError, sqlite.InterfaceError)
394 self.assertEqual(self.cx.DatabaseError, sqlite.DatabaseError)
395 self.assertEqual(self.cx.DataError, sqlite.DataError)
396 self.assertEqual(self.cx.OperationalError, sqlite.OperationalError)
397 self.assertEqual(self.cx.IntegrityError, sqlite.IntegrityError)
398 self.assertEqual(self.cx.InternalError, sqlite.InternalError)
399 self.assertEqual(self.cx.ProgrammingError, sqlite.ProgrammingError)
400 self.assertEqual(self.cx.NotSupportedError, sqlite.NotSupportedError)
401
402 def test_in_transaction(self):
403 # Can't use db from setUp because we want to test initial state.
404 with memory_database() as cx:
405 cu = cx.cursor()
406 self.assertEqual(cx.in_transaction, False)
407 cu.execute("create table transactiontest(id integer primary key, name text)")
408 self.assertEqual(cx.in_transaction, False)
409 cu.execute("insert into transactiontest(name) values (?)", ("foo",))
410 self.assertEqual(cx.in_transaction, True)
411 cu.execute("select name from transactiontest where name=?", ["foo"])
412 row = cu.fetchone()
413 self.assertEqual(cx.in_transaction, True)
414 cx.commit()
415 self.assertEqual(cx.in_transaction, False)
416 cu.execute("select name from transactiontest where name=?", ["foo"])
417 row = cu.fetchone()
418 self.assertEqual(cx.in_transaction, False)
419 cu.close()
420
421 def test_in_transaction_ro(self):
422 with self.assertRaises(AttributeError):
423 self.cx.in_transaction = True
424
425 def test_connection_exceptions(self):
426 exceptions = [
427 "DataError",
428 "DatabaseError",
429 "Error",
430 "IntegrityError",
431 "InterfaceError",
432 "NotSupportedError",
433 "OperationalError",
434 "ProgrammingError",
435 "Warning",
436 ]
437 for exc in exceptions:
438 with self.subTest(exc=exc):
439 self.assertTrue(hasattr(self.cx, exc))
440 self.assertIs(getattr(sqlite, exc), getattr(self.cx, exc))
441
442 def test_interrupt_on_closed_db(self):
443 self.cx.close()
444 with self.assertRaises(sqlite.ProgrammingError):
445 self.cx.interrupt()
446
447 def test_interrupt(self):
448 self.assertIsNone(self.cx.interrupt())
449
450 def test_drop_unused_refs(self):
451 for n in range(500):
452 cu = self.cx.execute(f"select {n}")
453 self.assertEqual(cu.fetchone()[0], n)
454
455 def test_connection_limits(self):
456 category = sqlite.SQLITE_LIMIT_SQL_LENGTH
457 saved_limit = self.cx.getlimit(category)
458 try:
459 new_limit = 10
460 prev_limit = self.cx.setlimit(category, new_limit)
461 self.assertEqual(saved_limit, prev_limit)
462 self.assertEqual(self.cx.getlimit(category), new_limit)
463 msg = "query string is too large"
464 self.assertRaisesRegex(sqlite.DataError, msg,
465 self.cx.execute, "select 1 as '16'")
466 finally: # restore saved limit
467 self.cx.setlimit(category, saved_limit)
468
469 def test_connection_bad_limit_category(self):
470 msg = "'category' is out of bounds"
471 cat = 1111
472 self.assertRaisesRegex(sqlite.ProgrammingError, msg,
473 self.cx.getlimit, cat)
474 self.assertRaisesRegex(sqlite.ProgrammingError, msg,
475 self.cx.setlimit, cat, 0)
476
477 def test_connection_init_bad_isolation_level(self):
478 msg = (
479 "isolation_level string must be '', 'DEFERRED', 'IMMEDIATE', or "
480 "'EXCLUSIVE'"
481 )
482 levels = (
483 "BOGUS",
484 " ",
485 "DEFERRE",
486 "IMMEDIAT",
487 "EXCLUSIV",
488 "DEFERREDS",
489 "IMMEDIATES",
490 "EXCLUSIVES",
491 )
492 for level in levels:
493 with self.subTest(level=level):
494 with self.assertRaisesRegex(ValueError, msg):
495 memory_database(isolation_level=level)
496 with memory_database() as cx:
497 with self.assertRaisesRegex(ValueError, msg):
498 cx.isolation_level = level
499 # Check that the default level is not changed
500 self.assertEqual(cx.isolation_level, "")
501
502 def test_connection_init_good_isolation_levels(self):
503 for level in ("", "DEFERRED", "IMMEDIATE", "EXCLUSIVE", None):
504 with self.subTest(level=level):
505 with memory_database(isolation_level=level) as cx:
506 self.assertEqual(cx.isolation_level, level)
507 with memory_database() as cx:
508 self.assertEqual(cx.isolation_level, "")
509 cx.isolation_level = level
510 self.assertEqual(cx.isolation_level, level)
511
512 def test_connection_reinit(self):
513 with memory_database() as cx:
514 cx.text_factory = bytes
515 cx.row_factory = sqlite.Row
516 cu = cx.cursor()
517 cu.execute("create table foo (bar)")
518 cu.executemany("insert into foo (bar) values (?)",
519 ((str(v),) for v in range(4)))
520 cu.execute("select bar from foo")
521
522 rows = [r for r in cu.fetchmany(2)]
523 self.assertTrue(all(isinstance(r, sqlite.Row) for r in rows))
524 self.assertEqual([r[0] for r in rows], [b"0", b"1"])
525
526 cx.__init__(":memory:")
527 cx.execute("create table foo (bar)")
528 cx.executemany("insert into foo (bar) values (?)",
529 ((v,) for v in ("a", "b", "c", "d")))
530
531 # This uses the old database, old row factory, but new text factory
532 rows = [r for r in cu.fetchall()]
533 self.assertTrue(all(isinstance(r, sqlite.Row) for r in rows))
534 self.assertEqual([r[0] for r in rows], ["2", "3"])
535 cu.close()
536
537 def test_connection_bad_reinit(self):
538 cx = sqlite.connect(":memory:")
539 with cx:
540 cx.execute("create table t(t)")
541 with temp_dir() as db:
542 self.assertRaisesRegex(sqlite.OperationalError,
543 "unable to open database file",
544 cx.__init__, db)
545 self.assertRaisesRegex(sqlite.ProgrammingError,
546 "Base Connection.__init__ not called",
547 cx.executemany, "insert into t values(?)",
548 ((v,) for v in range(3)))
549
550 def test_connection_config(self):
551 op = sqlite.SQLITE_DBCONFIG_ENABLE_FKEY
552 with memory_database() as cx:
553 with self.assertRaisesRegex(ValueError, "unknown"):
554 cx.getconfig(-1)
555
556 # Toggle and verify.
557 old = cx.getconfig(op)
558 new = not old
559 cx.setconfig(op, new)
560 self.assertEqual(cx.getconfig(op), new)
561
562 cx.setconfig(op) # defaults to True
563 self.assertTrue(cx.getconfig(op))
564
565 # Check that foreign key support was actually enabled.
566 with cx:
567 cx.executescript("""
568 create table t(t integer primary key);
569 create table u(u, foreign key(u) references t(t));
570 """)
571 with self.assertRaisesRegex(sqlite.IntegrityError, "constraint"):
572 cx.execute("insert into u values(0)")
573
574 def test_connect_positional_arguments(self):
575 regex = (
576 r"Passing more than 1 positional argument to sqlite3.connect\(\)"
577 " is deprecated. Parameters 'timeout', 'detect_types', "
578 "'isolation_level', 'check_same_thread', 'factory', "
579 "'cached_statements' and 'uri' will become keyword-only "
580 "parameters in Python 3.15."
581 )
582 with self.assertWarnsRegex(DeprecationWarning, regex) as cm:
583 cx = sqlite.connect(":memory:", 1.0)
584 cx.close()
585 self.assertEqual(cm.filename, __file__)
586
587 def test_connection_resource_warning(self):
588 with self.assertWarns(ResourceWarning):
589 cx = sqlite.connect(":memory:")
590 del cx
591 gc_collect()
592
593 def test_connection_signature(self):
594 from inspect import signature
595 sig = signature(self.cx)
596 self.assertEqual(str(sig), "(sql, /)")
597
598
599 class UninitialisedConnectionTests(unittest.TestCase):
600 def setUp(self):
601 self.cx = sqlite.Connection.__new__(sqlite.Connection)
602
603 def test_uninit_operations(self):
604 funcs = (
605 lambda: self.cx.isolation_level,
606 lambda: self.cx.total_changes,
607 lambda: self.cx.in_transaction,
608 lambda: self.cx.iterdump(),
609 lambda: self.cx.cursor(),
610 lambda: self.cx.close(),
611 )
612 for func in funcs:
613 with self.subTest(func=func):
614 self.assertRaisesRegex(sqlite.ProgrammingError,
615 "Base Connection.__init__ not called",
616 func)
617
618
619 @unittest.skipUnless(hasattr(sqlite.Connection, "serialize"),
620 "Needs SQLite serialize API")
621 class SerializeTests(unittest.TestCase):
622 def test_serialize_deserialize(self):
623 with memory_database() as cx:
624 with cx:
625 cx.execute("create table t(t)")
626 data = cx.serialize()
627
628 # Remove test table, verify that it was removed.
629 with cx:
630 cx.execute("drop table t")
631 regex = "no such table"
632 with self.assertRaisesRegex(sqlite.OperationalError, regex):
633 cx.execute("select t from t")
634
635 # Deserialize and verify that test table is restored.
636 cx.deserialize(data)
637 cx.execute("select t from t")
638
639 def test_deserialize_wrong_args(self):
640 dataset = (
641 (BufferError, memoryview(b"blob")[::2]),
642 (TypeError, []),
643 (TypeError, 1),
644 (TypeError, None),
645 )
646 for exc, arg in dataset:
647 with self.subTest(exc=exc, arg=arg):
648 with memory_database() as cx:
649 self.assertRaises(exc, cx.deserialize, arg)
650
651 def test_deserialize_corrupt_database(self):
652 with memory_database() as cx:
653 regex = "file is not a database"
654 with self.assertRaisesRegex(sqlite.DatabaseError, regex):
655 cx.deserialize(b"\0\1\3")
656 # SQLite does not generate an error until you try to query the
657 # deserialized database.
658 cx.execute("create table fail(f)")
659
660
661 class OpenTests(unittest.TestCase):
662 _sql = "create table test(id integer)"
663
664 def test_open_with_bytes_path(self):
665 path = os.fsencode(TESTFN)
666 self.addCleanup(unlink, path)
667 self.assertFalse(os.path.exists(path))
668 with contextlib.closing(sqlite.connect(path)) as cx:
669 self.assertTrue(os.path.exists(path))
670 cx.execute(self._sql)
671
672 def test_open_with_path_like_object(self):
673 """ Checks that we can successfully connect to a database using an object that
674 is PathLike, i.e. has __fspath__(). """
675 path = FakePath(TESTFN)
676 self.addCleanup(unlink, path)
677 self.assertFalse(os.path.exists(path))
678 with contextlib.closing(sqlite.connect(path)) as cx:
679 self.assertTrue(os.path.exists(path))
680 cx.execute(self._sql)
681
682 def get_undecodable_path(self):
683 path = TESTFN_UNDECODABLE
684 if not path:
685 self.skipTest("only works if there are undecodable paths")
686 try:
687 open(path, 'wb').close()
688 except OSError:
689 self.skipTest(f"can't create file with undecodable path {path!r}")
690 unlink(path)
691 return path
692
693 @unittest.skipIf(sys.platform == "win32", "skipped on Windows")
694 def test_open_with_undecodable_path(self):
695 path = self.get_undecodable_path()
696 self.addCleanup(unlink, path)
697 with contextlib.closing(sqlite.connect(path)) as cx:
698 self.assertTrue(os.path.exists(path))
699 cx.execute(self._sql)
700
701 def test_open_uri(self):
702 path = TESTFN
703 self.addCleanup(unlink, path)
704 uri = "file:" + urllib.parse.quote(os.fsencode(path))
705 self.assertFalse(os.path.exists(path))
706 with contextlib.closing(sqlite.connect(uri, uri=True)) as cx:
707 self.assertTrue(os.path.exists(path))
708 cx.execute(self._sql)
709
710 def test_open_unquoted_uri(self):
711 path = TESTFN
712 self.addCleanup(unlink, path)
713 uri = "file:" + path
714 self.assertFalse(os.path.exists(path))
715 with contextlib.closing(sqlite.connect(uri, uri=True)) as cx:
716 self.assertTrue(os.path.exists(path))
717 cx.execute(self._sql)
718
719 def test_open_uri_readonly(self):
720 path = TESTFN
721 self.addCleanup(unlink, path)
722 uri = "file:" + urllib.parse.quote(os.fsencode(path)) + "?mode=ro"
723 self.assertFalse(os.path.exists(path))
724 # Cannot create new DB
725 with self.assertRaises(sqlite.OperationalError):
726 sqlite.connect(uri, uri=True)
727 self.assertFalse(os.path.exists(path))
728 sqlite.connect(path).close()
729 self.assertTrue(os.path.exists(path))
730 # Cannot modify new DB
731 with contextlib.closing(sqlite.connect(uri, uri=True)) as cx:
732 with self.assertRaises(sqlite.OperationalError):
733 cx.execute(self._sql)
734
735 @unittest.skipIf(sys.platform == "win32", "skipped on Windows")
736 def test_open_undecodable_uri(self):
737 path = self.get_undecodable_path()
738 self.addCleanup(unlink, path)
739 uri = "file:" + urllib.parse.quote(path)
740 with contextlib.closing(sqlite.connect(uri, uri=True)) as cx:
741 self.assertTrue(os.path.exists(path))
742 cx.execute(self._sql)
743
744 def test_factory_database_arg(self):
745 def factory(database, *args, **kwargs):
746 nonlocal database_arg
747 database_arg = database
748 return sqlite.Connection(":memory:", *args, **kwargs)
749
750 for database in (TESTFN, os.fsencode(TESTFN),
751 FakePath(TESTFN), FakePath(os.fsencode(TESTFN))):
752 database_arg = None
753 sqlite.connect(database, factory=factory).close()
754 self.assertEqual(database_arg, database)
755
756 def test_database_keyword(self):
757 with contextlib.closing(sqlite.connect(database=":memory:")) as cx:
758 self.assertEqual(type(cx), sqlite.Connection)
759
760
761 class CursorTests(unittest.TestCase):
762 def setUp(self):
763 self.cx = sqlite.connect(":memory:")
764 self.cu = self.cx.cursor()
765 self.cu.execute(
766 "create table test(id integer primary key, name text, "
767 "income number, unique_test text unique)"
768 )
769 self.cu.execute("insert into test(name) values (?)", ("foo",))
770
771 def tearDown(self):
772 self.cu.close()
773 self.cx.close()
774
775 def test_execute_no_args(self):
776 self.cu.execute("delete from test")
777
778 def test_execute_illegal_sql(self):
779 with self.assertRaises(sqlite.OperationalError):
780 self.cu.execute("select asdf")
781
782 def test_execute_multiple_statements(self):
783 msg = "You can only execute one statement at a time"
784 dataset = (
785 "select 1; select 2",
786 "select 1; // c++ comments are not allowed",
787 "select 1; *not a comment",
788 "select 1; -*not a comment",
789 "select 1; /* */ a",
790 "select 1; /**/a",
791 "select 1; -",
792 "select 1; /",
793 "select 1; -\n- select 2",
794 """select 1;
795 -- comment
796 select 2
797 """,
798 )
799 for query in dataset:
800 with self.subTest(query=query):
801 with self.assertRaisesRegex(sqlite.ProgrammingError, msg):
802 self.cu.execute(query)
803
804 def test_execute_with_appended_comments(self):
805 dataset = (
806 "select 1; -- foo bar",
807 "select 1; --",
808 "select 1; /*", # Unclosed comments ending in \0 are skipped.
809 """
810 select 5+4;
811
812 /*
813 foo
814 */
815 """,
816 )
817 for query in dataset:
818 with self.subTest(query=query):
819 self.cu.execute(query)
820
821 def test_execute_wrong_sql_arg(self):
822 with self.assertRaises(TypeError):
823 self.cu.execute(42)
824
825 def test_execute_arg_int(self):
826 self.cu.execute("insert into test(id) values (?)", (42,))
827
828 def test_execute_arg_float(self):
829 self.cu.execute("insert into test(income) values (?)", (2500.32,))
830
831 def test_execute_arg_string(self):
832 self.cu.execute("insert into test(name) values (?)", ("Hugo",))
833
834 def test_execute_arg_string_with_zero_byte(self):
835 self.cu.execute("insert into test(name) values (?)", ("Hu\x00go",))
836
837 self.cu.execute("select name from test where id=?", (self.cu.lastrowid,))
838 row = self.cu.fetchone()
839 self.assertEqual(row[0], "Hu\x00go")
840
841 def test_execute_non_iterable(self):
842 with self.assertRaises(sqlite.ProgrammingError) as cm:
843 self.cu.execute("insert into test(id) values (?)", 42)
844 self.assertEqual(str(cm.exception), 'parameters are of unsupported type')
845
846 def test_execute_wrong_no_of_args1(self):
847 # too many parameters
848 with self.assertRaises(sqlite.ProgrammingError):
849 self.cu.execute("insert into test(id) values (?)", (17, "Egon"))
850
851 def test_execute_wrong_no_of_args2(self):
852 # too little parameters
853 with self.assertRaises(sqlite.ProgrammingError):
854 self.cu.execute("insert into test(id) values (?)")
855
856 def test_execute_wrong_no_of_args3(self):
857 # no parameters, parameters are needed
858 with self.assertRaises(sqlite.ProgrammingError):
859 self.cu.execute("insert into test(id) values (?)")
860
861 def test_execute_param_list(self):
862 self.cu.execute("insert into test(name) values ('foo')")
863 self.cu.execute("select name from test where name=?", ["foo"])
864 row = self.cu.fetchone()
865 self.assertEqual(row[0], "foo")
866
867 def test_execute_param_sequence(self):
868 class L:
869 def __len__(self):
870 return 1
871 def __getitem__(self, x):
872 assert x == 0
873 return "foo"
874
875 self.cu.execute("insert into test(name) values ('foo')")
876 self.cu.execute("select name from test where name=?", L())
877 row = self.cu.fetchone()
878 self.assertEqual(row[0], "foo")
879
880 def test_execute_param_sequence_bad_len(self):
881 # Issue41662: Error in __len__() was overridden with ProgrammingError.
882 class L:
883 def __len__(self):
884 1/0
885 def __getitem__(slf, x):
886 raise AssertionError
887
888 self.cu.execute("insert into test(name) values ('foo')")
889 with self.assertRaises(ZeroDivisionError):
890 self.cu.execute("select name from test where name=?", L())
891
892 def test_execute_named_param_and_sequence(self):
893 dataset = (
894 ("select :a", (1,)),
895 ("select :a, ?, ?", (1, 2, 3)),
896 ("select ?, :b, ?", (1, 2, 3)),
897 ("select ?, ?, :c", (1, 2, 3)),
898 ("select :a, :b, ?", (1, 2, 3)),
899 )
900 msg = "Binding.*is a named parameter"
901 for query, params in dataset:
902 with self.subTest(query=query, params=params):
903 with self.assertWarnsRegex(DeprecationWarning, msg) as cm:
904 self.cu.execute(query, params)
905 self.assertEqual(cm.filename, __file__)
906
907 def test_execute_indexed_nameless_params(self):
908 # See gh-117995: "'?1' is considered a named placeholder"
909 for query, params, expected in (
910 ("select ?1, ?2", (1, 2), (1, 2)),
911 ("select ?2, ?1", (1, 2), (2, 1)),
912 ):
913 with self.subTest(query=query, params=params):
914 with warnings.catch_warnings():
915 warnings.simplefilter("error", DeprecationWarning)
916 cu = self.cu.execute(query, params)
917 actual, = cu.fetchall()
918 self.assertEqual(actual, expected)
919
920 def test_execute_too_many_params(self):
921 category = sqlite.SQLITE_LIMIT_VARIABLE_NUMBER
922 msg = "too many SQL variables"
923 with cx_limit(self.cx, category=category, limit=1):
924 self.cu.execute("select * from test where id=?", (1,))
925 with self.assertRaisesRegex(sqlite.OperationalError, msg):
926 self.cu.execute("select * from test where id!=? and id!=?",
927 (1, 2))
928
929 def test_execute_dict_mapping(self):
930 self.cu.execute("insert into test(name) values ('foo')")
931 self.cu.execute("select name from test where name=:name", {"name": "foo"})
932 row = self.cu.fetchone()
933 self.assertEqual(row[0], "foo")
934
935 def test_execute_dict_mapping_mapping(self):
936 class D(dict):
937 def __missing__(self, key):
938 return "foo"
939
940 self.cu.execute("insert into test(name) values ('foo')")
941 self.cu.execute("select name from test where name=:name", D())
942 row = self.cu.fetchone()
943 self.assertEqual(row[0], "foo")
944
945 def test_execute_dict_mapping_too_little_args(self):
946 self.cu.execute("insert into test(name) values ('foo')")
947 with self.assertRaises(sqlite.ProgrammingError):
948 self.cu.execute("select name from test where name=:name and id=:id", {"name": "foo"})
949
950 def test_execute_dict_mapping_no_args(self):
951 self.cu.execute("insert into test(name) values ('foo')")
952 with self.assertRaises(sqlite.ProgrammingError):
953 self.cu.execute("select name from test where name=:name")
954
955 def test_execute_dict_mapping_unnamed(self):
956 self.cu.execute("insert into test(name) values ('foo')")
957 with self.assertRaises(sqlite.ProgrammingError):
958 self.cu.execute("select name from test where name=?", {"name": "foo"})
959
960 def test_close(self):
961 self.cu.close()
962
963 def test_rowcount_execute(self):
964 self.cu.execute("delete from test")
965 self.cu.execute("insert into test(name) values ('foo')")
966 self.cu.execute("insert into test(name) values ('foo')")
967 self.cu.execute("update test set name='bar'")
968 self.assertEqual(self.cu.rowcount, 2)
969
970 def test_rowcount_select(self):
971 """
972 pysqlite does not know the rowcount of SELECT statements, because we
973 don't fetch all rows after executing the select statement. The rowcount
974 has thus to be -1.
975 """
976 self.cu.execute("select 5 union select 6")
977 self.assertEqual(self.cu.rowcount, -1)
978
979 def test_rowcount_executemany(self):
980 self.cu.execute("delete from test")
981 self.cu.executemany("insert into test(name) values (?)", [(1,), (2,), (3,)])
982 self.assertEqual(self.cu.rowcount, 3)
983
984 @unittest.skipIf(sqlite.sqlite_version_info < (3, 35, 0),
985 "Requires SQLite 3.35.0 or newer")
986 def test_rowcount_update_returning(self):
987 # gh-93421: rowcount is updated correctly for UPDATE...RETURNING queries
988 self.cu.execute("update test set name='bar' where name='foo' returning 1")
989 self.assertEqual(self.cu.fetchone()[0], 1)
990 self.assertEqual(self.cu.rowcount, 1)
991
992 def test_rowcount_prefixed_with_comment(self):
993 # gh-79579: rowcount is updated even if query is prefixed with comments
994 self.cu.execute("""
995 -- foo
996 insert into test(name) values ('foo'), ('foo')
997 """)
998 self.assertEqual(self.cu.rowcount, 2)
999 self.cu.execute("""
1000 /* -- messy *r /* /* ** *- *--
1001 */
1002 /* one more */ insert into test(name) values ('messy')
1003 """)
1004 self.assertEqual(self.cu.rowcount, 1)
1005 self.cu.execute("/* bar */ update test set name='bar' where name='foo'")
1006 self.assertEqual(self.cu.rowcount, 3)
1007
1008 def test_rowcount_vaccuum(self):
1009 data = ((1,), (2,), (3,))
1010 self.cu.executemany("insert into test(income) values(?)", data)
1011 self.assertEqual(self.cu.rowcount, 3)
1012 self.cx.commit()
1013 self.cu.execute("vacuum")
1014 self.assertEqual(self.cu.rowcount, -1)
1015
1016 def test_total_changes(self):
1017 self.cu.execute("insert into test(name) values ('foo')")
1018 self.cu.execute("insert into test(name) values ('foo')")
1019 self.assertLess(2, self.cx.total_changes, msg='total changes reported wrong value')
1020
1021 # Checks for executemany:
1022 # Sequences are required by the DB-API, iterators
1023 # enhancements in pysqlite.
1024
1025 def test_execute_many_sequence(self):
1026 self.cu.executemany("insert into test(income) values (?)", [(x,) for x in range(100, 110)])
1027
1028 def test_execute_many_iterator(self):
1029 class MyIter:
1030 def __init__(self):
1031 self.value = 5
1032
1033 def __iter__(self):
1034 return self
1035
1036 def __next__(self):
1037 if self.value == 10:
1038 raise StopIteration
1039 else:
1040 self.value += 1
1041 return (self.value,)
1042
1043 self.cu.executemany("insert into test(income) values (?)", MyIter())
1044
1045 def test_execute_many_generator(self):
1046 def mygen():
1047 for i in range(5):
1048 yield (i,)
1049
1050 self.cu.executemany("insert into test(income) values (?)", mygen())
1051
1052 def test_execute_many_wrong_sql_arg(self):
1053 with self.assertRaises(TypeError):
1054 self.cu.executemany(42, [(3,)])
1055
1056 def test_execute_many_select(self):
1057 with self.assertRaises(sqlite.ProgrammingError):
1058 self.cu.executemany("select ?", [(3,)])
1059
1060 def test_execute_many_not_iterable(self):
1061 with self.assertRaises(TypeError):
1062 self.cu.executemany("insert into test(income) values (?)", 42)
1063
1064 def test_fetch_iter(self):
1065 # Optional DB-API extension.
1066 self.cu.execute("delete from test")
1067 self.cu.execute("insert into test(id) values (?)", (5,))
1068 self.cu.execute("insert into test(id) values (?)", (6,))
1069 self.cu.execute("select id from test order by id")
1070 lst = []
1071 for row in self.cu:
1072 lst.append(row[0])
1073 self.assertEqual(lst[0], 5)
1074 self.assertEqual(lst[1], 6)
1075
1076 def test_fetchone(self):
1077 self.cu.execute("select name from test")
1078 row = self.cu.fetchone()
1079 self.assertEqual(row[0], "foo")
1080 row = self.cu.fetchone()
1081 self.assertEqual(row, None)
1082
1083 def test_fetchone_no_statement(self):
1084 cur = self.cx.cursor()
1085 row = cur.fetchone()
1086 self.assertEqual(row, None)
1087
1088 def test_array_size(self):
1089 # must default to 1
1090 self.assertEqual(self.cu.arraysize, 1)
1091
1092 # now set to 2
1093 self.cu.arraysize = 2
1094
1095 # now make the query return 2 rows from a table of 3 rows
1096 self.cu.execute("delete from test")
1097 self.cu.execute("insert into test(name) values ('A')")
1098 self.cu.execute("insert into test(name) values ('B')")
1099 self.cu.execute("insert into test(name) values ('C')")
1100 self.cu.execute("select name from test")
1101 res = self.cu.fetchmany()
1102
1103 self.assertEqual(len(res), 2)
1104
1105 def test_invalid_array_size(self):
1106 UINT32_MAX = (1 << 32) - 1
1107 setter = functools.partial(setattr, self.cu, 'arraysize')
1108
1109 self.assertRaises(TypeError, setter, 1.0)
1110 self.assertRaises(ValueError, setter, -3)
1111 self.assertRaises(OverflowError, setter, UINT32_MAX + 1)
1112
1113 def test_fetchmany(self):
1114 # no active SQL statement
1115 res = self.cu.fetchmany()
1116 self.assertEqual(res, [])
1117 res = self.cu.fetchmany(1000)
1118 self.assertEqual(res, [])
1119
1120 # test default parameter
1121 self.cu.execute("select name from test")
1122 res = self.cu.fetchmany()
1123 self.assertEqual(len(res), 1)
1124
1125 # test when the number of requested rows exceeds the actual count
1126 self.cu.execute("select name from test")
1127 res = self.cu.fetchmany(100)
1128 self.assertEqual(len(res), 1)
1129 res = self.cu.fetchmany(100)
1130 self.assertEqual(res, [])
1131
1132 # test when size = 0
1133 self.cu.execute("select name from test")
1134 res = self.cu.fetchmany(0)
1135 self.assertEqual(res, [])
1136 res = self.cu.fetchmany(100)
1137 self.assertEqual(len(res), 1)
1138 res = self.cu.fetchmany(100)
1139 self.assertEqual(res, [])
1140
1141 def test_invalid_fetchmany(self):
1142 UINT32_MAX = (1 << 32) - 1
1143 fetchmany = self.cu.fetchmany
1144
1145 self.assertRaises(TypeError, fetchmany, 1.0)
1146 self.assertRaises(ValueError, fetchmany, -3)
1147 self.assertRaises(OverflowError, fetchmany, UINT32_MAX + 1)
1148
1149 def test_fetchmany_kw_arg(self):
1150 """Checks if fetchmany works with keyword arguments"""
1151 self.cu.execute("select name from test")
1152 res = self.cu.fetchmany(size=100)
1153 self.assertEqual(len(res), 1)
1154
1155 def test_fetchall(self):
1156 self.cu.execute("select name from test")
1157 res = self.cu.fetchall()
1158 self.assertEqual(len(res), 1)
1159 res = self.cu.fetchall()
1160 self.assertEqual(res, [])
1161
1162 def test_setinputsizes(self):
1163 self.cu.setinputsizes([3, 4, 5])
1164
1165 def test_setoutputsize(self):
1166 self.cu.setoutputsize(5, 0)
1167
1168 def test_setoutputsize_no_column(self):
1169 self.cu.setoutputsize(42)
1170
1171 def test_cursor_connection(self):
1172 # Optional DB-API extension.
1173 self.assertEqual(self.cu.connection, self.cx)
1174
1175 def test_wrong_cursor_callable(self):
1176 with self.assertRaises(TypeError):
1177 def f(): pass
1178 cur = self.cx.cursor(f)
1179
1180 def test_cursor_wrong_class(self):
1181 class Foo: pass
1182 foo = Foo()
1183 with self.assertRaises(TypeError):
1184 cur = sqlite.Cursor(foo)
1185
1186 def test_last_row_id_on_replace(self):
1187 """
1188 INSERT OR REPLACE and REPLACE INTO should produce the same behavior.
1189 """
1190 sql = '{} INTO test(id, unique_test) VALUES (?, ?)'
1191 for statement in ('INSERT OR REPLACE', 'REPLACE'):
1192 with self.subTest(statement=statement):
1193 self.cu.execute(sql.format(statement), (1, 'foo'))
1194 self.assertEqual(self.cu.lastrowid, 1)
1195
1196 def test_last_row_id_on_ignore(self):
1197 self.cu.execute(
1198 "insert or ignore into test(unique_test) values (?)",
1199 ('test',))
1200 self.assertEqual(self.cu.lastrowid, 2)
1201 self.cu.execute(
1202 "insert or ignore into test(unique_test) values (?)",
1203 ('test',))
1204 self.assertEqual(self.cu.lastrowid, 2)
1205
1206 def test_last_row_id_insert_o_r(self):
1207 results = []
1208 for statement in ('FAIL', 'ABORT', 'ROLLBACK'):
1209 sql = 'INSERT OR {} INTO test(unique_test) VALUES (?)'
1210 with self.subTest(statement='INSERT OR {}'.format(statement)):
1211 self.cu.execute(sql.format(statement), (statement,))
1212 results.append((statement, self.cu.lastrowid))
1213 with self.assertRaises(sqlite.IntegrityError):
1214 self.cu.execute(sql.format(statement), (statement,))
1215 results.append((statement, self.cu.lastrowid))
1216 expected = [
1217 ('FAIL', 2), ('FAIL', 2),
1218 ('ABORT', 3), ('ABORT', 3),
1219 ('ROLLBACK', 4), ('ROLLBACK', 4),
1220 ]
1221 self.assertEqual(results, expected)
1222
1223 def test_column_count(self):
1224 # Check that column count is updated correctly for cached statements
1225 select = "select * from test"
1226 res = self.cu.execute(select)
1227 old_count = len(res.description)
1228 # Add a new column and execute the cached select query again
1229 self.cu.execute("alter table test add newcol")
1230 res = self.cu.execute(select)
1231 new_count = len(res.description)
1232 self.assertEqual(new_count - old_count, 1)
1233
1234 def test_same_query_in_multiple_cursors(self):
1235 cursors = [self.cx.execute("select 1") for _ in range(3)]
1236 for cu in cursors:
1237 self.assertEqual(cu.fetchall(), [(1,)])
1238
1239
1240 class BlobTests(unittest.TestCase):
1241 def setUp(self):
1242 self.cx = sqlite.connect(":memory:")
1243 self.cx.execute("create table test(b blob)")
1244 self.data = b"this blob data string is exactly fifty bytes long!"
1245 self.cx.execute("insert into test(b) values (?)", (self.data,))
1246 self.blob = self.cx.blobopen("test", "b", 1)
1247
1248 def tearDown(self):
1249 self.blob.close()
1250 self.cx.close()
1251
1252 def test_blob_is_a_blob(self):
1253 self.assertIsInstance(self.blob, sqlite.Blob)
1254
1255 def test_blob_seek_and_tell(self):
1256 self.blob.seek(10)
1257 self.assertEqual(self.blob.tell(), 10)
1258
1259 self.blob.seek(10, SEEK_SET)
1260 self.assertEqual(self.blob.tell(), 10)
1261
1262 self.blob.seek(10, SEEK_CUR)
1263 self.assertEqual(self.blob.tell(), 20)
1264
1265 self.blob.seek(-10, SEEK_END)
1266 self.assertEqual(self.blob.tell(), 40)
1267
1268 def test_blob_seek_error(self):
1269 msg_oor = "offset out of blob range"
1270 msg_orig = "'origin' should be os.SEEK_SET, os.SEEK_CUR, or os.SEEK_END"
1271
1272 dataset = (
1273 (ValueError, msg_oor, lambda: self.blob.seek(1000)),
1274 (ValueError, msg_oor, lambda: self.blob.seek(-10)),
1275 (ValueError, msg_orig, lambda: self.blob.seek(10, -1)),
1276 (ValueError, msg_orig, lambda: self.blob.seek(10, 3)),
1277 )
1278 for exc, msg, fn in dataset:
1279 with self.subTest(exc=exc, msg=msg, fn=fn):
1280 self.assertRaisesRegex(exc, msg, fn)
1281
1282 def test_blob_seek_overflow_error(self):
1283 # Force overflow errors
1284 msg_of = "seek offset results in overflow"
1285 _testcapi = import_helper.import_module("_testcapi")
1286 self.blob.seek(1, SEEK_SET)
1287 with self.assertRaisesRegex(OverflowError, msg_of):
1288 self.blob.seek(_testcapi.INT_MAX, SEEK_CUR)
1289 with self.assertRaisesRegex(OverflowError, msg_of):
1290 self.blob.seek(_testcapi.INT_MAX, SEEK_END)
1291
1292 def test_blob_read(self):
1293 buf = self.blob.read()
1294 self.assertEqual(buf, self.data)
1295
1296 def test_blob_read_oversized(self):
1297 buf = self.blob.read(len(self.data) * 2)
1298 self.assertEqual(buf, self.data)
1299
1300 def test_blob_read_advance_offset(self):
1301 n = 10
1302 buf = self.blob.read(n)
1303 self.assertEqual(buf, self.data[:n])
1304 self.assertEqual(self.blob.tell(), n)
1305
1306 def test_blob_read_at_offset(self):
1307 self.blob.seek(10)
1308 self.assertEqual(self.blob.read(10), self.data[10:20])
1309
1310 def test_blob_read_error_row_changed(self):
1311 self.cx.execute("update test set b='aaaa' where rowid=1")
1312 with self.assertRaises(sqlite.OperationalError):
1313 self.blob.read()
1314
1315 def test_blob_write(self):
1316 new_data = b"new data".ljust(50)
1317 self.blob.write(new_data)
1318 row = self.cx.execute("select b from test").fetchone()
1319 self.assertEqual(row[0], new_data)
1320
1321 def test_blob_write_at_offset(self):
1322 new_data = b"c" * 25
1323 self.blob.seek(25)
1324 self.blob.write(new_data)
1325 row = self.cx.execute("select b from test").fetchone()
1326 self.assertEqual(row[0], self.data[:25] + new_data)
1327
1328 def test_blob_write_advance_offset(self):
1329 self.blob.write(b"d"*10)
1330 self.assertEqual(self.blob.tell(), 10)
1331
1332 def test_blob_write_error_length(self):
1333 with self.assertRaisesRegex(ValueError, "data longer than blob"):
1334 self.blob.write(b"a" * 1000)
1335
1336 self.blob.seek(0, SEEK_SET)
1337 n = len(self.blob)
1338 self.blob.write(b"a" * (n-1))
1339 self.blob.write(b"a")
1340 with self.assertRaisesRegex(ValueError, "data longer than blob"):
1341 self.blob.write(b"a")
1342
1343 def test_blob_write_error_row_changed(self):
1344 self.cx.execute("update test set b='aaaa' where rowid=1")
1345 with self.assertRaises(sqlite.OperationalError):
1346 self.blob.write(b"aaa")
1347
1348 def test_blob_write_error_readonly(self):
1349 ro_blob = self.cx.blobopen("test", "b", 1, readonly=True)
1350 with self.assertRaisesRegex(sqlite.OperationalError, "readonly"):
1351 ro_blob.write(b"aaa")
1352 ro_blob.close()
1353
1354 def test_blob_open_error(self):
1355 dataset = (
1356 (("test", "b", 1), {"name": "notexisting"}),
1357 (("notexisting", "b", 1), {}),
1358 (("test", "notexisting", 1), {}),
1359 (("test", "b", 2), {}),
1360 )
1361 regex = "no such"
1362 for args, kwds in dataset:
1363 with self.subTest(args=args, kwds=kwds):
1364 with self.assertRaisesRegex(sqlite.OperationalError, regex):
1365 self.cx.blobopen(*args, **kwds)
1366
1367 def test_blob_length(self):
1368 self.assertEqual(len(self.blob), 50)
1369
1370 def test_blob_get_item(self):
1371 self.assertEqual(self.blob[5], ord("b"))
1372 self.assertEqual(self.blob[6], ord("l"))
1373 self.assertEqual(self.blob[7], ord("o"))
1374 self.assertEqual(self.blob[8], ord("b"))
1375 self.assertEqual(self.blob[-1], ord("!"))
1376
1377 def test_blob_set_item(self):
1378 self.blob[0] = ord("b")
1379 expected = b"b" + self.data[1:]
1380 actual = self.cx.execute("select b from test").fetchone()[0]
1381 self.assertEqual(actual, expected)
1382
1383 def test_blob_set_item_with_offset(self):
1384 self.blob.seek(0, SEEK_END)
1385 self.assertEqual(self.blob.read(), b"") # verify that we're at EOB
1386 self.blob[0] = ord("T")
1387 self.blob[-1] = ord(".")
1388 self.blob.seek(0, SEEK_SET)
1389 expected = b"This blob data string is exactly fifty bytes long."
1390 self.assertEqual(self.blob.read(), expected)
1391
1392 def test_blob_set_slice_buffer_object(self):
1393 from array import array
1394 self.blob[0:5] = memoryview(b"12345")
1395 self.assertEqual(self.blob[0:5], b"12345")
1396
1397 self.blob[0:5] = bytearray(b"23456")
1398 self.assertEqual(self.blob[0:5], b"23456")
1399
1400 self.blob[0:5] = array("b", [1, 2, 3, 4, 5])
1401 self.assertEqual(self.blob[0:5], b"\x01\x02\x03\x04\x05")
1402
1403 def test_blob_set_item_negative_index(self):
1404 self.blob[-1] = 255
1405 self.assertEqual(self.blob[-1], 255)
1406
1407 def test_blob_get_slice(self):
1408 self.assertEqual(self.blob[5:14], b"blob data")
1409
1410 def test_blob_get_empty_slice(self):
1411 self.assertEqual(self.blob[5:5], b"")
1412
1413 def test_blob_get_slice_negative_index(self):
1414 self.assertEqual(self.blob[5:-5], self.data[5:-5])
1415
1416 def test_blob_get_slice_with_skip(self):
1417 self.assertEqual(self.blob[0:10:2], b"ti lb")
1418
1419 def test_blob_set_slice(self):
1420 self.blob[0:5] = b"12345"
1421 expected = b"12345" + self.data[5:]
1422 actual = self.cx.execute("select b from test").fetchone()[0]
1423 self.assertEqual(actual, expected)
1424
1425 def test_blob_set_empty_slice(self):
1426 self.blob[0:0] = b""
1427 self.assertEqual(self.blob[:], self.data)
1428
1429 def test_blob_set_slice_with_skip(self):
1430 self.blob[0:10:2] = b"12345"
1431 actual = self.cx.execute("select b from test").fetchone()[0]
1432 expected = b"1h2s3b4o5 " + self.data[10:]
1433 self.assertEqual(actual, expected)
1434
1435 def test_blob_mapping_invalid_index_type(self):
1436 msg = "indices must be integers"
1437 with self.assertRaisesRegex(TypeError, msg):
1438 self.blob[5:5.5]
1439 with self.assertRaisesRegex(TypeError, msg):
1440 self.blob[1.5]
1441 with self.assertRaisesRegex(TypeError, msg):
1442 self.blob["a"] = b"b"
1443
1444 def test_blob_get_item_error(self):
1445 dataset = [len(self.blob), 105, -105]
1446 for idx in dataset:
1447 with self.subTest(idx=idx):
1448 with self.assertRaisesRegex(IndexError, "index out of range"):
1449 self.blob[idx]
1450
1451 # Provoke read error
1452 self.cx.execute("update test set b='aaaa' where rowid=1")
1453 with self.assertRaises(sqlite.OperationalError):
1454 self.blob[0]
1455
1456 def test_blob_get_item_error_bigint(self):
1457 _testcapi = import_helper.import_module("_testcapi")
1458 with self.assertRaisesRegex(IndexError, "cannot fit 'int'"):
1459 self.blob[_testcapi.ULLONG_MAX]
1460
1461 def test_blob_set_item_error(self):
1462 with self.assertRaisesRegex(TypeError, "cannot be interpreted"):
1463 self.blob[0] = b"multiple"
1464 with self.assertRaisesRegex(TypeError, "cannot be interpreted"):
1465 self.blob[0] = b"1"
1466 with self.assertRaisesRegex(TypeError, "cannot be interpreted"):
1467 self.blob[0] = bytearray(b"1")
1468 with self.assertRaisesRegex(TypeError, "doesn't support.*deletion"):
1469 del self.blob[0]
1470 with self.assertRaisesRegex(IndexError, "Blob index out of range"):
1471 self.blob[1000] = 0
1472 with self.assertRaisesRegex(ValueError, "must be in range"):
1473 self.blob[0] = -1
1474 with self.assertRaisesRegex(ValueError, "must be in range"):
1475 self.blob[0] = 256
1476 # Overflow errors are overridden with ValueError
1477 with self.assertRaisesRegex(ValueError, "must be in range"):
1478 self.blob[0] = 2**65
1479
1480 def test_blob_set_slice_error(self):
1481 with self.assertRaisesRegex(IndexError, "wrong size"):
1482 self.blob[5:10] = b"a"
1483 with self.assertRaisesRegex(IndexError, "wrong size"):
1484 self.blob[5:10] = b"a" * 1000
1485 with self.assertRaisesRegex(TypeError, "doesn't support.*deletion"):
1486 del self.blob[5:10]
1487 with self.assertRaisesRegex(ValueError, "step cannot be zero"):
1488 self.blob[5:10:0] = b"12345"
1489 with self.assertRaises(BufferError):
1490 self.blob[5:10] = memoryview(b"abcde")[::2]
1491
1492 def test_blob_sequence_not_supported(self):
1493 with self.assertRaisesRegex(TypeError, "unsupported operand"):
1494 self.blob + self.blob
1495 with self.assertRaisesRegex(TypeError, "unsupported operand"):
1496 self.blob * 5
1497 with self.assertRaisesRegex(TypeError, "is not iterable"):
1498 b"a" in self.blob
1499
1500 def test_blob_context_manager(self):
1501 data = b"a" * 50
1502 with self.cx.blobopen("test", "b", 1) as blob:
1503 blob.write(data)
1504 actual = self.cx.execute("select b from test").fetchone()[0]
1505 self.assertEqual(actual, data)
1506
1507 # Check that __exit__ closed the blob
1508 with self.assertRaisesRegex(sqlite.ProgrammingError, "closed blob"):
1509 blob.read()
1510
1511 def test_blob_context_manager_reraise_exceptions(self):
1512 class DummyException(Exception):
1513 pass
1514 with self.assertRaisesRegex(DummyException, "reraised"):
1515 with self.cx.blobopen("test", "b", 1) as blob:
1516 raise DummyException("reraised")
1517
1518
1519 def test_blob_closed(self):
1520 with memory_database() as cx:
1521 cx.execute("create table test(b blob)")
1522 cx.execute("insert into test values (zeroblob(100))")
1523 blob = cx.blobopen("test", "b", 1)
1524 blob.close()
1525
1526 msg = "Cannot operate on a closed blob"
1527 with self.assertRaisesRegex(sqlite.ProgrammingError, msg):
1528 blob.read()
1529 with self.assertRaisesRegex(sqlite.ProgrammingError, msg):
1530 blob.write(b"")
1531 with self.assertRaisesRegex(sqlite.ProgrammingError, msg):
1532 blob.seek(0)
1533 with self.assertRaisesRegex(sqlite.ProgrammingError, msg):
1534 blob.tell()
1535 with self.assertRaisesRegex(sqlite.ProgrammingError, msg):
1536 blob.__enter__()
1537 with self.assertRaisesRegex(sqlite.ProgrammingError, msg):
1538 blob.__exit__(None, None, None)
1539 with self.assertRaisesRegex(sqlite.ProgrammingError, msg):
1540 len(blob)
1541 with self.assertRaisesRegex(sqlite.ProgrammingError, msg):
1542 blob[0]
1543 with self.assertRaisesRegex(sqlite.ProgrammingError, msg):
1544 blob[0:1]
1545 with self.assertRaisesRegex(sqlite.ProgrammingError, msg):
1546 blob[0] = b""
1547
1548 def test_blob_closed_db_read(self):
1549 with memory_database() as cx:
1550 cx.execute("create table test(b blob)")
1551 cx.execute("insert into test(b) values (zeroblob(100))")
1552 blob = cx.blobopen("test", "b", 1)
1553 cx.close()
1554 self.assertRaisesRegex(sqlite.ProgrammingError,
1555 "Cannot operate on a closed database",
1556 blob.read)
1557
1558 def test_blob_32bit_rowid(self):
1559 # gh-100370: we should not get an OverflowError for 32-bit rowids
1560 with memory_database() as cx:
1561 rowid = 2**32
1562 cx.execute("create table t(t blob)")
1563 cx.execute("insert into t(rowid, t) values (?, zeroblob(1))", (rowid,))
1564 cx.blobopen('t', 't', rowid)
1565
1566
1567 @threading_helper.requires_working_threading()
1568 class ThreadTests(unittest.TestCase):
1569 def setUp(self):
1570 self.con = sqlite.connect(":memory:")
1571 self.cur = self.con.cursor()
1572 self.cur.execute("create table test(name text, b blob)")
1573 self.cur.execute("insert into test values('blob', zeroblob(1))")
1574
1575 def tearDown(self):
1576 self.cur.close()
1577 self.con.close()
1578
1579 @threading_helper.reap_threads
1580 def _run_test(self, fn, *args, **kwds):
1581 def run(err):
1582 try:
1583 fn(*args, **kwds)
1584 err.append("did not raise ProgrammingError")
1585 except sqlite.ProgrammingError:
1586 pass
1587 except:
1588 err.append("raised wrong exception")
1589
1590 err = []
1591 t = threading.Thread(target=run, kwargs={"err": err})
1592 t.start()
1593 t.join()
1594 if err:
1595 self.fail("\n".join(err))
1596
1597 def test_check_connection_thread(self):
1598 fns = [
1599 lambda: self.con.cursor(),
1600 lambda: self.con.commit(),
1601 lambda: self.con.rollback(),
1602 lambda: self.con.close(),
1603 lambda: self.con.set_trace_callback(None),
1604 lambda: self.con.set_authorizer(None),
1605 lambda: self.con.create_collation("foo", None),
1606 lambda: self.con.setlimit(sqlite.SQLITE_LIMIT_LENGTH, -1),
1607 lambda: self.con.getlimit(sqlite.SQLITE_LIMIT_LENGTH),
1608 lambda: self.con.blobopen("test", "b", 1),
1609 ]
1610 if hasattr(sqlite.Connection, "serialize"):
1611 fns.append(lambda: self.con.serialize())
1612 fns.append(lambda: self.con.deserialize(b""))
1613 if sqlite.sqlite_version_info >= (3, 25, 0):
1614 fns.append(lambda: self.con.create_window_function("foo", 0, None))
1615
1616 for fn in fns:
1617 with self.subTest(fn=fn):
1618 self._run_test(fn)
1619
1620 def test_check_cursor_thread(self):
1621 fns = [
1622 lambda: self.cur.execute("insert into test(name) values('a')"),
1623 lambda: self.cur.close(),
1624 lambda: self.cur.execute("select name from test"),
1625 lambda: self.cur.fetchone(),
1626 ]
1627 for fn in fns:
1628 with self.subTest(fn=fn):
1629 self._run_test(fn)
1630
1631
1632 @threading_helper.reap_threads
1633 def test_dont_check_same_thread(self):
1634 def run(con, err):
1635 try:
1636 con.execute("select 1")
1637 except sqlite.Error:
1638 err.append("multi-threading not allowed")
1639
1640 with memory_database(check_same_thread=False) as con:
1641 err = []
1642 t = threading.Thread(target=run, kwargs={"con": con, "err": err})
1643 t.start()
1644 t.join()
1645 self.assertEqual(len(err), 0, "\n".join(err))
1646
1647
1648 class ConstructorTests(unittest.TestCase):
1649 def test_date(self):
1650 d = sqlite.Date(2004, 10, 28)
1651
1652 def test_time(self):
1653 t = sqlite.Time(12, 39, 35)
1654
1655 def test_timestamp(self):
1656 ts = sqlite.Timestamp(2004, 10, 28, 12, 39, 35)
1657
1658 def test_date_from_ticks(self):
1659 d = sqlite.DateFromTicks(42)
1660
1661 def test_time_from_ticks(self):
1662 t = sqlite.TimeFromTicks(42)
1663
1664 def test_timestamp_from_ticks(self):
1665 ts = sqlite.TimestampFromTicks(42)
1666
1667 def test_binary(self):
1668 b = sqlite.Binary(b"\0'")
1669
1670 class ExtensionTests(unittest.TestCase):
1671 def setUp(self):
1672 self.con = sqlite.connect(":memory:")
1673 self.cur = self.con.cursor()
1674
1675 def tearDown(self):
1676 self.cur.close()
1677 self.con.close()
1678
1679 def test_script_string_sql(self):
1680 cur = self.cur
1681 cur.executescript("""
1682 -- bla bla
1683 /* a stupid comment */
1684 create table a(i);
1685 insert into a(i) values (5);
1686 """)
1687 cur.execute("select i from a")
1688 res = cur.fetchone()[0]
1689 self.assertEqual(res, 5)
1690
1691 def test_script_syntax_error(self):
1692 with self.assertRaises(sqlite.OperationalError):
1693 self.cur.executescript("""
1694 CREATE TABLE test(x);
1695 asdf;
1696 CREATE TABLE test2(x)
1697 """)
1698
1699 def test_script_error_normal(self):
1700 with self.assertRaises(sqlite.OperationalError):
1701 self.cur.executescript("""
1702 CREATE TABLE test(sadfsadfdsa);
1703 SELECT foo FROM hurz;
1704 """)
1705
1706 def test_cursor_executescript_as_bytes(self):
1707 with self.assertRaises(TypeError):
1708 self.cur.executescript(b"""
1709 CREATE TABLE test(foo);
1710 INSERT INTO test(foo) VALUES (5);
1711 """)
1712
1713 def test_cursor_executescript_with_null_characters(self):
1714 with self.assertRaises(ValueError):
1715 self.cur.executescript("""
1716 CREATE TABLE a(i);\0
1717 INSERT INTO a(i) VALUES (5);
1718 """)
1719
1720 def test_cursor_executescript_with_surrogates(self):
1721 with self.assertRaises(UnicodeEncodeError):
1722 self.cur.executescript("""
1723 CREATE TABLE a(s);
1724 INSERT INTO a(s) VALUES ('\ud8ff');
1725 """)
1726
1727 def test_cursor_executescript_too_large_script(self):
1728 msg = "query string is too large"
1729 with memory_database() as cx, cx_limit(cx) as lim:
1730 cx.executescript("select 'almost too large'".ljust(lim))
1731 with self.assertRaisesRegex(sqlite.DataError, msg):
1732 cx.executescript("select 'too large'".ljust(lim+1))
1733
1734 def test_cursor_executescript_tx_control(self):
1735 con = self.con
1736 con.execute("begin")
1737 self.assertTrue(con.in_transaction)
1738 con.executescript("select 1")
1739 self.assertFalse(con.in_transaction)
1740
1741 def test_connection_execute(self):
1742 result = self.con.execute("select 5").fetchone()[0]
1743 self.assertEqual(result, 5, "Basic test of Connection.execute")
1744
1745 def test_connection_executemany(self):
1746 con = self.con
1747 con.execute("create table test(foo)")
1748 con.executemany("insert into test(foo) values (?)", [(3,), (4,)])
1749 result = con.execute("select foo from test order by foo").fetchall()
1750 self.assertEqual(result[0][0], 3, "Basic test of Connection.executemany")
1751 self.assertEqual(result[1][0], 4, "Basic test of Connection.executemany")
1752
1753 def test_connection_executescript(self):
1754 con = self.con
1755 con.executescript("""
1756 CREATE TABLE test(foo);
1757 INSERT INTO test(foo) VALUES (5);
1758 """)
1759 result = con.execute("select foo from test").fetchone()[0]
1760 self.assertEqual(result, 5, "Basic test of Connection.executescript")
1761
1762
1763 class ClosedConTests(unittest.TestCase):
1764 def check(self, fn, *args, **kwds):
1765 regex = "Cannot operate on a closed database."
1766 with self.assertRaisesRegex(sqlite.ProgrammingError, regex):
1767 fn(*args, **kwds)
1768
1769 def setUp(self):
1770 self.con = sqlite.connect(":memory:")
1771 self.cur = self.con.cursor()
1772 self.con.close()
1773
1774 def test_closed_con_cursor(self):
1775 self.check(self.con.cursor)
1776
1777 def test_closed_con_commit(self):
1778 self.check(self.con.commit)
1779
1780 def test_closed_con_rollback(self):
1781 self.check(self.con.rollback)
1782
1783 def test_closed_cur_execute(self):
1784 self.check(self.cur.execute, "select 4")
1785
1786 def test_closed_create_function(self):
1787 def f(x):
1788 return 17
1789 self.check(self.con.create_function, "foo", 1, f)
1790
1791 def test_closed_create_aggregate(self):
1792 class Agg:
1793 def __init__(self):
1794 pass
1795 def step(self, x):
1796 pass
1797 def finalize(self):
1798 return 17
1799 self.check(self.con.create_aggregate, "foo", 1, Agg)
1800
1801 def test_closed_set_authorizer(self):
1802 def authorizer(*args):
1803 return sqlite.DENY
1804 self.check(self.con.set_authorizer, authorizer)
1805
1806 def test_closed_set_progress_callback(self):
1807 def progress():
1808 pass
1809 self.check(self.con.set_progress_handler, progress, 100)
1810
1811 def test_closed_call(self):
1812 self.check(self.con)
1813
1814
1815 class ClosedCurTests(MemoryDatabaseMixin, unittest.TestCase):
1816 def test_closed(self):
1817 cur = self.cx.cursor()
1818 cur.close()
1819
1820 for method_name in ("execute", "executemany", "executescript", "fetchall", "fetchmany", "fetchone"):
1821 if method_name in ("execute", "executescript"):
1822 params = ("select 4 union select 5",)
1823 elif method_name == "executemany":
1824 params = ("insert into foo(bar) values (?)", [(3,), (4,)])
1825 else:
1826 params = []
1827
1828 with self.assertRaises(sqlite.ProgrammingError):
1829 method = getattr(cur, method_name)
1830 method(*params)
1831
1832
1833 class SqliteOnConflictTests(unittest.TestCase):
1834 """
1835 Tests for SQLite's "insert on conflict" feature.
1836
1837 See https://www.sqlite.org/lang_conflict.html for details.
1838 """
1839
1840 def setUp(self):
1841 self.cx = sqlite.connect(":memory:")
1842 self.cu = self.cx.cursor()
1843 self.cu.execute("""
1844 CREATE TABLE test(
1845 id INTEGER PRIMARY KEY, name TEXT, unique_name TEXT UNIQUE
1846 );
1847 """)
1848
1849 def tearDown(self):
1850 self.cu.close()
1851 self.cx.close()
1852
1853 def test_on_conflict_rollback_with_explicit_transaction(self):
1854 self.cx.isolation_level = None # autocommit mode
1855 self.cu = self.cx.cursor()
1856 # Start an explicit transaction.
1857 self.cu.execute("BEGIN")
1858 self.cu.execute("INSERT INTO test(name) VALUES ('abort_test')")
1859 self.cu.execute("INSERT OR ROLLBACK INTO test(unique_name) VALUES ('foo')")
1860 with self.assertRaises(sqlite.IntegrityError):
1861 self.cu.execute("INSERT OR ROLLBACK INTO test(unique_name) VALUES ('foo')")
1862 # Use connection to commit.
1863 self.cx.commit()
1864 self.cu.execute("SELECT name, unique_name from test")
1865 # Transaction should have rolled back and nothing should be in table.
1866 self.assertEqual(self.cu.fetchall(), [])
1867
1868 def test_on_conflict_abort_raises_with_explicit_transactions(self):
1869 # Abort cancels the current sql statement but doesn't change anything
1870 # about the current transaction.
1871 self.cx.isolation_level = None # autocommit mode
1872 self.cu = self.cx.cursor()
1873 # Start an explicit transaction.
1874 self.cu.execute("BEGIN")
1875 self.cu.execute("INSERT INTO test(name) VALUES ('abort_test')")
1876 self.cu.execute("INSERT OR ABORT INTO test(unique_name) VALUES ('foo')")
1877 with self.assertRaises(sqlite.IntegrityError):
1878 self.cu.execute("INSERT OR ABORT INTO test(unique_name) VALUES ('foo')")
1879 self.cx.commit()
1880 self.cu.execute("SELECT name, unique_name FROM test")
1881 # Expect the first two inserts to work, third to do nothing.
1882 self.assertEqual(self.cu.fetchall(), [('abort_test', None), (None, 'foo',)])
1883
1884 def test_on_conflict_rollback_without_transaction(self):
1885 # Start of implicit transaction
1886 self.cu.execute("INSERT INTO test(name) VALUES ('abort_test')")
1887 self.cu.execute("INSERT OR ROLLBACK INTO test(unique_name) VALUES ('foo')")
1888 with self.assertRaises(sqlite.IntegrityError):
1889 self.cu.execute("INSERT OR ROLLBACK INTO test(unique_name) VALUES ('foo')")
1890 self.cu.execute("SELECT name, unique_name FROM test")
1891 # Implicit transaction is rolled back on error.
1892 self.assertEqual(self.cu.fetchall(), [])
1893
1894 def test_on_conflict_abort_raises_without_transactions(self):
1895 # Abort cancels the current sql statement but doesn't change anything
1896 # about the current transaction.
1897 self.cu.execute("INSERT INTO test(name) VALUES ('abort_test')")
1898 self.cu.execute("INSERT OR ABORT INTO test(unique_name) VALUES ('foo')")
1899 with self.assertRaises(sqlite.IntegrityError):
1900 self.cu.execute("INSERT OR ABORT INTO test(unique_name) VALUES ('foo')")
1901 # Make sure all other values were inserted.
1902 self.cu.execute("SELECT name, unique_name FROM test")
1903 self.assertEqual(self.cu.fetchall(), [('abort_test', None), (None, 'foo',)])
1904
1905 def test_on_conflict_fail(self):
1906 self.cu.execute("INSERT OR FAIL INTO test(unique_name) VALUES ('foo')")
1907 with self.assertRaises(sqlite.IntegrityError):
1908 self.cu.execute("INSERT OR FAIL INTO test(unique_name) VALUES ('foo')")
1909 self.assertEqual(self.cu.fetchall(), [])
1910
1911 def test_on_conflict_ignore(self):
1912 self.cu.execute("INSERT OR IGNORE INTO test(unique_name) VALUES ('foo')")
1913 # Nothing should happen.
1914 self.cu.execute("INSERT OR IGNORE INTO test(unique_name) VALUES ('foo')")
1915 self.cu.execute("SELECT unique_name FROM test")
1916 self.assertEqual(self.cu.fetchall(), [('foo',)])
1917
1918 def test_on_conflict_replace(self):
1919 self.cu.execute("INSERT OR REPLACE INTO test(name, unique_name) VALUES ('Data!', 'foo')")
1920 # There shouldn't be an IntegrityError exception.
1921 self.cu.execute("INSERT OR REPLACE INTO test(name, unique_name) VALUES ('Very different data!', 'foo')")
1922 self.cu.execute("SELECT name, unique_name FROM test")
1923 self.assertEqual(self.cu.fetchall(), [('Very different data!', 'foo')])
1924
1925
1926 @requires_subprocess()
1927 class MultiprocessTests(unittest.TestCase):
1928 CONNECTION_TIMEOUT = 0 # Disable the busy timeout.
1929
1930 def tearDown(self):
1931 unlink(TESTFN)
1932
1933 def test_ctx_mgr_rollback_if_commit_failed(self):
1934 # bpo-27334: ctx manager does not rollback if commit fails
1935 SCRIPT = f"""if 1:
1936 import sqlite3
1937 def wait():
1938 print("started")
1939 assert "database is locked" in input()
1940
1941 cx = sqlite3.connect("{TESTFN}", timeout={self.CONNECTION_TIMEOUT})
1942 cx.create_function("wait", 0, wait)
1943 with cx:
1944 cx.execute("create table t(t)")
1945 try:
1946 # execute two transactions; both will try to lock the db
1947 cx.executescript('''
1948 -- start a transaction and wait for parent
1949 begin transaction;
1950 select * from t;
1951 select wait();
1952 rollback;
1953
1954 -- start a new transaction; would fail if parent holds lock
1955 begin transaction;
1956 select * from t;
1957 rollback;
1958 ''')
1959 finally:
1960 cx.close()
1961 """
1962
1963 # spawn child process
1964 proc = subprocess.Popen(
1965 [sys.executable, "-c", SCRIPT],
1966 encoding="utf-8",
1967 bufsize=0,
1968 stdin=subprocess.PIPE,
1969 stdout=subprocess.PIPE,
1970 )
1971 self.addCleanup(proc.communicate)
1972
1973 # wait for child process to start
1974 self.assertEqual("started", proc.stdout.readline().strip())
1975
1976 cx = sqlite.connect(TESTFN, timeout=self.CONNECTION_TIMEOUT)
1977 try: # context manager should correctly release the db lock
1978 with cx:
1979 cx.execute("insert into t values('test')")
1980 except sqlite.OperationalError as exc:
1981 proc.stdin.write(str(exc))
1982 else:
1983 proc.stdin.write("no error")
1984 finally:
1985 cx.close()
1986
1987 # terminate child process
1988 self.assertIsNone(proc.returncode)
1989 try:
1990 proc.communicate(input="end", timeout=SHORT_TIMEOUT)
1991 except subprocess.TimeoutExpired:
1992 proc.kill()
1993 proc.communicate()
1994 raise
1995 self.assertEqual(proc.returncode, 0)
1996
1997
1998 class RowTests(unittest.TestCase):
1999
2000 def setUp(self):
2001 self.cx = sqlite.connect(":memory:")
2002 self.cx.row_factory = sqlite.Row
2003
2004 def tearDown(self):
2005 self.cx.close()
2006
2007 def test_row_keys(self):
2008 cu = self.cx.execute("SELECT 1 as first, 2 as second")
2009 row = cu.fetchone()
2010 self.assertEqual(row.keys(), ["first", "second"])
2011
2012 def test_row_length(self):
2013 cu = self.cx.execute("SELECT 1, 2, 3")
2014 row = cu.fetchone()
2015 self.assertEqual(len(row), 3)
2016
2017 def test_row_getitem(self):
2018 cu = self.cx.execute("SELECT 1 as a, 2 as b")
2019 row = cu.fetchone()
2020 self.assertEqual(row[0], 1)
2021 self.assertEqual(row[1], 2)
2022 self.assertEqual(row["a"], 1)
2023 self.assertEqual(row["b"], 2)
2024 for key in "nokey", 4, 1.2:
2025 with self.subTest(key=key):
2026 with self.assertRaises(IndexError):
2027 row[key]
2028
2029 def test_row_equality(self):
2030 c1 = self.cx.execute("SELECT 1 as a")
2031 r1 = c1.fetchone()
2032
2033 c2 = self.cx.execute("SELECT 1 as a")
2034 r2 = c2.fetchone()
2035
2036 self.assertIsNot(r1, r2)
2037 self.assertEqual(r1, r2)
2038
2039 c3 = self.cx.execute("SELECT 1 as b")
2040 r3 = c3.fetchone()
2041
2042 self.assertNotEqual(r1, r3)
2043
2044 def test_row_no_description(self):
2045 cu = self.cx.cursor()
2046 self.assertIsNone(cu.description)
2047
2048 row = sqlite.Row(cu, ())
2049 self.assertEqual(row.keys(), [])
2050 with self.assertRaisesRegex(IndexError, "nokey"):
2051 row["nokey"]
2052
2053 def test_row_is_a_sequence(self):
2054 from collections.abc import Sequence
2055
2056 cu = self.cx.execute("SELECT 1")
2057 row = cu.fetchone()
2058
2059 self.assertTrue(issubclass(sqlite.Row, Sequence))
2060 self.assertTrue(isinstance(row, Sequence))
2061
2062
2063 if __name__ == "__main__":
2064 unittest.main()