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