Debian Codegraph @

extra_tests/test_sqlite3.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """Tests for _sqlite3.py"""
3
4 from __future__ import absolute_import
5 import pytest
6 import sys
7 import gc
8 import io
9 import contextlib
10
11 _sqlite3 = pytest.importorskip('_sqlite3')
12
13 pypy_only = pytest.mark.skipif('__pypy__' not in sys.builtin_module_names,
14 reason="PyPy-only test")
15
16
17 @pytest.fixture
18 def con():
19 con = _sqlite3.connect(':memory:')
20 yield con
21 con.close()
22
23 con2 = con # allow using two connections
24
25
26 def test_list_ddl(con):
27 """From issue996. Mostly just looking for lack of exceptions."""
28 cursor = con.cursor()
29 cursor.execute('CREATE TABLE foo (bar INTEGER)')
30 result = list(cursor)
31 assert result == []
32 cursor.execute('INSERT INTO foo (bar) VALUES (42)')
33 result = list(cursor)
34 assert result == []
35 cursor.execute('SELECT * FROM foo')
36 result = list(cursor)
37 assert result == [(42,)]
38
39 @pypy_only
40 def test_connect_takes_same_positional_args_as_Connection(con):
41 from inspect import getfullargspec
42 clsargs = getfullargspec(_sqlite3.Connection.__init__).args[1:] # ignore self
43 conargs = getfullargspec(_sqlite3.connect).args
44 assert clsargs == conargs
45
46 def test_total_changes_after_close(con):
47 con.close()
48 with pytest.raises(_sqlite3.ProgrammingError):
49 con.total_changes
50
51 def test_connection_check_init():
52 class Connection(_sqlite3.Connection):
53 def __init__(self, name):
54 pass
55
56 con = Connection(":memory:")
57 with pytest.raises(_sqlite3.ProgrammingError) as excinfo:
58 con.cursor()
59 assert '__init__' in str(excinfo.value)
60
61
62 def test_cursor_check_init(con):
63 class Cursor(_sqlite3.Cursor):
64 def __init__(self, name):
65 pass
66
67 cur = Cursor(con)
68 with pytest.raises(_sqlite3.ProgrammingError) as excinfo:
69 cur.execute('select 1')
70 assert '__init__' in str(excinfo.value)
71
72 def test_connection_after_close(con):
73 with pytest.raises(TypeError):
74 con()
75 con.close()
76 # raises ProgrammingError because should check closed before check args
77 with pytest.raises(_sqlite3.ProgrammingError):
78 con()
79
80 def test_cursor_iter(con):
81 cur = con.cursor()
82 with pytest.raises(StopIteration):
83 next(cur)
84
85 cur.execute('select 1')
86 next(cur)
87 with pytest.raises(StopIteration):
88 next(cur)
89
90 cur.execute('select 1')
91 con.commit()
92 next(cur)
93 with pytest.raises(StopIteration):
94 next(cur)
95
96 cur.executemany('select 1', [])
97 with pytest.raises(StopIteration):
98 next(cur)
99
100 cur.execute('select 1')
101 cur.execute('create table test(ing)')
102 with pytest.raises(StopIteration):
103 next(cur)
104
105 cur.execute('select 1')
106 cur.execute('insert into test values(1)')
107 con.commit()
108 with pytest.raises(StopIteration):
109 next(cur)
110
111 def test_cursor_after_close(con):
112 cur = con.execute('select 1')
113 cur.close()
114 con.close()
115 with pytest.raises(_sqlite3.ProgrammingError):
116 cur.close()
117 # raises ProgrammingError because should check closed before check args
118 with pytest.raises(_sqlite3.ProgrammingError):
119 cur.execute(1,2,3,4,5)
120 with pytest.raises(_sqlite3.ProgrammingError):
121 cur.executemany(1,2,3,4,5)
122
123 def test_connection_del(tmpdir):
124 """For issue1325."""
125 import os
126 import gc
127 resource = pytest.importorskip('resource')
128
129 limit = resource.getrlimit(resource.RLIMIT_NOFILE)
130 try:
131 fds = 0
132 while True:
133 fds += 1
134 resource.setrlimit(resource.RLIMIT_NOFILE, (fds, limit[1]))
135 try:
136 for p in os.pipe(): os.close(p)
137 except OSError:
138 assert fds < 100
139 else:
140 break
141
142 def open_many(cleanup):
143 con = []
144 for i in range(3):
145 con.append(_sqlite3.connect(str(tmpdir.join('test.db'))))
146 if cleanup:
147 con[i] = None
148 gc.collect(); gc.collect()
149
150 def assert_fds_limit_triggers_operational_error():
151 with pytest.raises(_sqlite3.OperationalError):
152 open_many(False)
153 assert_fds_limit_triggers_operational_error()
154 gc.collect(); gc.collect()
155 open_many(True)
156 finally:
157 resource.setrlimit(resource.RLIMIT_NOFILE, limit)
158
159 def test_on_conflict_rollback_executemany(con):
160 major, minor, micro = _sqlite3.sqlite_version.split('.')[:3]
161 if (int(major), int(minor), int(micro)) < (3, 2, 2):
162 pytest.skip("requires sqlite3 version >= 3.2.2")
163 con.execute("create table foo(x, unique(x) on conflict rollback)")
164 con.execute("insert into foo(x) values (1)")
165 try:
166 con.executemany("insert into foo(x) values (?)", [[1]])
167 except _sqlite3.DatabaseError:
168 pass
169 con.execute("insert into foo(x) values (2)")
170 try:
171 con.commit()
172 except _sqlite3.OperationalError:
173 pytest.fail("_sqlite3 knew nothing about the implicit ROLLBACK")
174
175 def test_statement_arg_checking(con):
176 with pytest.raises(TypeError) as e:
177 con(123)
178 with pytest.raises(TypeError) as e:
179 con.execute(123)
180 with pytest.raises(TypeError) as e:
181 con.executemany(123, 123)
182 with pytest.raises(TypeError) as e:
183 con.executescript(123)
184 assert str(e.value).startswith('script argument must be unicode')
185
186 def test_statement_param_checking(con):
187 con.execute('create table foo(x)')
188 con.execute('insert into foo(x) values (?)', [2])
189 con.execute('insert into foo(x) values (?)', (2,))
190 class seq(object):
191 def __len__(self):
192 return 1
193 def __getitem__(self, key):
194 return 2
195 con.execute('insert into foo(x) values (?)', seq())
196 del seq.__len__
197 with pytest.raises(_sqlite3.ProgrammingError):
198 con.execute('insert into foo(x) values (?)', seq())
199 with pytest.raises(_sqlite3.ProgrammingError):
200 con.execute('insert into foo(x) values (?)', {2:2})
201 with pytest.raises(_sqlite3.ProgrammingError) as e:
202 con.execute('insert into foo(x) values (?)', 2)
203 assert str(e.value) == 'parameters are of unsupported type'
204
205 def test_explicit_begin(con):
206 con.execute('BEGIN')
207 with pytest.raises(_sqlite3.OperationalError):
208 con.execute('BEGIN ')
209 con.commit()
210 con.execute('BEGIN')
211 con.commit()
212
213 def test_row_factory_use(con):
214 con.row_factory = 42
215 con.execute('select 1')
216
217 def test_returning_blob_must_own_memory(con):
218 con.create_function("returnblob", 0, lambda: memoryview(b"blob"))
219 cur = con.execute("select returnblob()")
220 val = cur.fetchone()[0]
221 assert isinstance(val, bytes)
222
223 def test_function_arg_str_null_char(con):
224 con.create_function("strlen", 1, lambda a: len(a))
225 cur = con.execute("select strlen(?)", ["x\0y"])
226 val = cur.fetchone()[0]
227 assert val == 3
228
229
230 def test_description_after_fetchall(con):
231 cur = con.cursor()
232 assert cur.description is None
233 cur.execute("select 42").fetchall()
234 assert cur.description is not None
235
236 def test_executemany_lastrowid(con):
237 cur = con.cursor()
238 cur.execute("create table test(a)")
239 cur.executemany("insert into test values (?)", [[1], [2], [3]])
240 assert cur.lastrowid == 0
241 # issue 2682
242 cur.execute('''insert
243 into test
244 values (?)
245 ''', (1, ))
246 assert cur.lastrowid
247 cur.execute('''insert\t into test values (?) ''', (1, ))
248 assert cur.lastrowid
249
250 def test_authorizer_bad_value(con):
251 def authorizer_cb(action, arg1, arg2, dbname, source):
252 return 42
253 con.set_authorizer(authorizer_cb)
254 with pytest.raises(_sqlite3.OperationalError) as e:
255 con.execute('select 123')
256 major, minor, micro = _sqlite3.sqlite_version.split('.')[:3]
257 if (int(major), int(minor), int(micro)) >= (3, 6, 14):
258 assert str(e.value) == 'authorizer malfunction'
259 else:
260 assert str(e.value) == \
261 ("illegal return value (1) from the authorization function - "
262 "should be SQLITE_OK, SQLITE_IGNORE, or SQLITE_DENY")
263
264 def test_authorizer_clear(con):
265 def authorizer_cb(action, arg1, arg2, dbname, source):
266 return _sqlite3.SQLITE_DENY
267 con.set_authorizer(authorizer_cb)
268 with pytest.raises(_sqlite3.DatabaseError) as e:
269 con.execute('select 123')
270 con.set_authorizer(None)
271 con.execute('select 123')
272
273 def test_issue1573(con):
274 cur = con.cursor()
275 cur.execute(u'SELECT 1 as méil')
276 assert cur.description[0][0] == u"méil"
277
278 def test_adapter_exception(con):
279 def cast(obj):
280 raise ZeroDivisionError
281
282 _sqlite3.register_adapter(int, cast)
283 try:
284 cur = con.cursor()
285 with pytest.raises(ZeroDivisionError):
286 cur.execute("select ?", (4,))
287 finally:
288 del _sqlite3.adapters[(int, _sqlite3.PrepareProtocol)]
289 _sqlite3.BASE_TYPE_ADAPTED = False
290
291 def test_null_character(con):
292 if not hasattr(_sqlite3, '_ffi') and sys.version_info < (2, 7, 9):
293 pytest.skip("_sqlite3 too old")
294 with pytest.raises(_sqlite3.ProgrammingError) as excinfo:
295 con("\0select 1")
296 assert str(excinfo.value) == "the query contains a null character"
297 with pytest.raises(_sqlite3.ProgrammingError) as excinfo:
298 con("select 1\0")
299 assert str(excinfo.value) == "the query contains a null character"
300 cur = con.cursor()
301 with pytest.raises(_sqlite3.ProgrammingError) as excinfo:
302 cur.execute("\0select 2")
303 assert str(excinfo.value) == "the query contains a null character"
304 with pytest.raises(_sqlite3.ProgrammingError) as excinfo:
305 cur.execute("select 2\0")
306 assert str(excinfo.value) == "the query contains a null character"
307
308 def test_close_in_del_ordering():
309 import gc
310 class SQLiteBackend(object):
311 success = False
312 def __init__(self):
313 self.connection = _sqlite3.connect(":memory:")
314 def close(self):
315 self.connection.close()
316 def __del__(self):
317 self.close()
318 SQLiteBackend.success = True
319 def create_db_if_needed(self):
320 conn = self.connection
321 cursor = conn.cursor()
322 cursor.execute("""
323 create table if not exists nameoftable(value text)
324 """)
325 cursor.close()
326 conn.commit()
327 SQLiteBackend().create_db_if_needed()
328 gc.collect()
329 gc.collect()
330 assert SQLiteBackend.success
331
332 def test_locked_table(con):
333 con.execute("CREATE TABLE foo(x)")
334 con.execute("INSERT INTO foo(x) VALUES (?)", [42])
335 cur = con.execute("SELECT * FROM foo") # foo() is locked while cur is active
336 with pytest.raises(_sqlite3.OperationalError):
337 con.execute("DROP TABLE foo")
338
339 def test_cursor_close(con):
340 con.execute("CREATE TABLE foo(x)")
341 con.execute("INSERT INTO foo(x) VALUES (?)", [42])
342 cur = con.execute("SELECT * FROM foo")
343 cur.close()
344 con.execute("DROP TABLE foo") # no error
345
346 def test_cursor_del(con):
347 con.execute("CREATE TABLE foo(x)")
348 con.execute("INSERT INTO foo(x) VALUES (?)", [42])
349 con.execute("SELECT * FROM foo")
350 import gc; gc.collect()
351 con.execute("DROP TABLE foo") # no error
352
353 def test_open_path():
354 class P:
355 def __fspath__(self):
356 return b":memory:"
357 _sqlite3.connect(P())
358
359 def test_isolation_bug():
360 con = _sqlite3.connect(":memory:", isolation_level=None)
361 #con = _sqlite3.connect(":memory:")
362 #con.isolation_level = None
363 cur = con.cursor()
364 cur.execute("create table foo(x);")
365
366 def test_reset_of_shared_statement(con):
367 con = _sqlite3.connect(':memory:')
368 c0 = con.cursor()
369 c0.execute('CREATE TABLE data(n int, t int)')
370 # insert two values
371 c0.execute('INSERT INTO data(n, t) VALUES(?, ?)', (0, 1))
372 c0.execute('INSERT INTO data(n, t) VALUES(?, ?)', (1, 2))
373
374 c1 = con.execute('select * from data')
375 list(c1) # c1's statement is no longer in use afterwards
376 c2 = con.execute('select * from data')
377 # the statement between c1 and c2 is shared
378 assert c1._Cursor__statement is c2._Cursor__statement
379 val = next(c2)
380 assert val == (0, 1)
381 c1 = None # make c1 unreachable
382 gc.collect() # calling c1.__del__ used to reset c2._Cursor__statement!
383 val = next(c2)
384 assert val == (1, 2)
385 with pytest.raises(StopIteration):
386 next(c2)
387
388 def test_row_index_unicode(con):
389 import sqlite3
390 con.row_factory = sqlite3.Row
391 row = con.execute("select 1 as \xff").fetchone()
392 assert row["\xff"] == 1
393 with pytest.raises(IndexError):
394 row['\u0178']
395 with pytest.raises(IndexError):
396 row['\xdf']
397
398 @pytest.mark.skipif(not hasattr(_sqlite3.Connection, "backup"), reason="no backup")
399 class TestBackup:
400 def test_target_is_connection(self, con):
401 with pytest.raises(TypeError):
402 con.backup(None)
403
404 def test_target_different_self(self, con):
405 with pytest.raises(ValueError):
406 con.backup(con)
407
408 def test_progress_callable(self, con, con2):
409 with pytest.raises(TypeError):
410 con.backup(con2, progress=34)
411
412 def test_backup_simple(self, con, con2):
413 cursor = con.cursor()
414 con.execute('CREATE TABLE foo (key INTEGER)')
415 con.executemany('INSERT INTO foo (key) VALUES (?)', [(3,), (4,)])
416 con.commit()
417
418 con.backup(con2)
419 result = con2.execute("SELECT key FROM foo ORDER BY key").fetchall()
420 assert result[0][0] == 3
421 assert result[1][0] == 4
422
423 def test_reset_already_committed_statements_bug(con):
424 con.execute('''CREATE TABLE COMPANY
425 (ID INT PRIMARY KEY,
426 A INT);''')
427 con.execute("INSERT INTO COMPANY (ID, A) \
428 VALUES (1, 2)")
429 cursor = con.execute("SELECT id, a from COMPANY")
430 con.commit()
431 con.execute("DROP TABLE COMPANY")
432
433 def test_empty_statement():
434 r = _sqlite3.connect(":memory:")
435 cur = r.cursor()
436 for sql in ["", " ", "/*comment*/"]:
437 r = cur.execute(sql)
438 assert r.description is None
439 assert cur.fetchall() == []
440
441 def test_uninit_connection():
442 con = _sqlite3.Connection.__new__(_sqlite3.Connection)
443 with pytest.raises(_sqlite3.ProgrammingError):
444 con.isolation_level
445 with pytest.raises(_sqlite3.ProgrammingError):
446 con.total_changes
447 with pytest.raises(_sqlite3.ProgrammingError):
448 con.in_transaction
449 with pytest.raises(_sqlite3.ProgrammingError):
450 con.iterdump()
451 with pytest.raises(_sqlite3.ProgrammingError):
452 con.close()
453
454 @pypy_only
455 @pytest.mark.parametrize(
456 "param",
457 (
458 bytearray([1, 2, 3]),
459 3.14,
460 42,
461 "i <3 pypy",
462 b"i <3 pypy",
463 None,
464 ),
465 )
466 def test_need_adapt_optimization(param, con):
467 adapters = dict(_sqlite3.adapters)
468
469 def adapter(param):
470 """dummy adapter that adapts only non-basetypes"""
471 return 42
472
473 assert _sqlite3.BASE_TYPE_ADAPTED == False
474
475 # check that the fast path works for base types
476 old_adapt = _sqlite3.adapt
477 try:
478 _sqlite3.adapt = None
479 cur = con.cursor()
480 cur.execute("SELECT ?", (param,))
481
482 assert cur.fetchone() == (param,)
483 finally:
484 _sqlite3.adapt = old_adapt
485
486 # check that if an adapter for a base type has been registered,
487 # the behaviour is as expected
488 try:
489 _sqlite3.register_adapter(type(param), adapter)
490 assert _sqlite3.BASE_TYPE_ADAPTED == True
491 cur = con.cursor()
492 cur.execute("SELECT ?", (param,))
493
494 assert cur.fetchone() == (42,)
495 finally:
496 _sqlite3.adapters = adapters
497 _sqlite3.BASE_TYPE_ADAPTED = False
498
499 def test_description_insert():
500 conn = _sqlite3.connect(":memory:")
501
502 cursor = conn.cursor()
503
504 cursor.execute("""create table foo (x int, y int)""")
505 cursor.execute(
506 """insert into foo (x, y) values (1, 1), (2, 2), (3, 3), (4, 4)"""
507 )
508 cursor.execute(
509 """insert into foo (x, y) values (5, 5), (6, 6)
510 RETURNING x, y"""
511 )
512
513 assert cursor.description == (
514 ("x", None, None, None, None, None, None),
515 ("y", None, None, None, None, None, None),
516 )
517
518
519 def test_description_update():
520 conn = _sqlite3.connect(":memory:")
521
522 cursor = conn.cursor()
523
524 cursor.execute("""create table foo (x int, y int)""")
525 cursor.execute(
526 """insert into foo (x, y) values (1, 1), (2, 2), (3, 3), (4, 4)"""
527 )
528 cursor.execute(
529 """update foo set y=y+5 where x in (2, 3)
530 RETURNING x, y"""
531 )
532
533 assert cursor.description == (
534 ("x", None, None, None, None, None, None),
535 ("y", None, None, None, None, None, None),
536 )
537
538
539 def test_description_delete():
540 conn = _sqlite3.connect(":memory:")
541
542 cursor = conn.cursor()
543
544 cursor.execute("""create table foo (x int, y int)""")
545 cursor.execute(
546 """insert into foo (x, y) values (1, 1), (2, 2), (3, 3), (4, 4)"""
547 )
548 cursor.execute(
549 """delete from foo where x in (1, 4)
550 RETURNING x, y"""
551 )
552
553 assert cursor.description == (
554 ("x", None, None, None, None, None, None),
555 ("y", None, None, None, None, None, None),
556 )
557
558 def test_description_parse_colnames():
559 conn = _sqlite3.connect(":memory:")
560 cur = conn.cursor()
561 cur.execute(u'SELECT 1 as "m [ä]"')
562 assert cur.description[0][0] == u"m [ä]"
563
564 def bar(x):
565 return x
566 try:
567 _sqlite3.converters['Ä'] = bar
568 conn = _sqlite3.connect(":memory:", detect_types=_sqlite3.PARSE_COLNAMES)
569 cur = conn.cursor()
570 cur.execute(u'SELECT 1 as "m [ä]"')
571 assert cur.description[0][0] == u"m"
572 finally:
573 del _sqlite3.converters['Ä']
574
575
576 def test_recursive_close():
577 conn = _sqlite3.connect(":memory:", detect_types=_sqlite3.PARSE_COLNAMES)
578 cursor = conn.cursor()
579 cursor.execute("create table test(x foo)")
580 cursor.executemany("insert into test(x) values (?)",
581 [("foo",), ("bar",)])
582 def conv(x):
583 cursor.close()
584 return x
585 try:
586 _sqlite3.converters['CLOSE'] = conv
587 with pytest.raises(_sqlite3.ProgrammingError):
588 cursor.execute(f'select x as "x [CLOSE]", x from test')
589 next(cursor)
590 finally:
591 del _sqlite3.converters['CLOSE']
592
593 def test_recursive_fetch():
594 conn = _sqlite3.connect(":memory:", detect_types=_sqlite3.PARSE_COLNAMES)
595 cursor = conn.cursor()
596 cursor.execute("create table test(x foo)")
597 cursor.executemany("insert into test(x) values (?)",
598 [("foo",), ("bar",)])
599 l = []
600 def conv(x):
601 cursor.fetchone()
602 return x
603 try:
604 _sqlite3.converters['ITER'] = conv
605 with pytest.raises(_sqlite3.ProgrammingError):
606 cursor.execute(f'select x as "x [ITER]", x from test')
607 next(cursor)
608 finally:
609 del _sqlite3.converters['ITER']
610
611 def test_recursive_init():
612 conn = _sqlite3.connect(":memory:", detect_types=_sqlite3.PARSE_COLNAMES)
613 cursor = conn.cursor()
614 cursor.execute("create table test(x foo)")
615 cursor.executemany("insert into test(x) values (?)",
616 [("foo",), ("bar",)])
617 def conv(x):
618 cursor.__init__(conn)
619 return x
620 try:
621 _sqlite3.converters['INIT'] = conv
622 with pytest.raises(_sqlite3.ProgrammingError):
623 cursor.execute(f'select x as "x [INIT]", x from test')
624 next(cursor)
625 finally:
626 del _sqlite3.converters['INIT']
627
628 def test_complete_statement():
629 # tested in stdlib for cpython 3.11+
630 assert not _sqlite3.complete_statement("SELECT") # missing ';'
631 assert _sqlite3.complete_statement("SELECT foo FROM bar;")
632
633 def test_enable_callback_traceback():
634 # tested in stdlib for cpython 3.11+
635 def bad_progress():
636 1 // 0
637
638 con = _sqlite3.connect(":memory:")
639 con.set_progress_handler(bad_progress, 1)
640 # sanity check
641 with pytest.raises(_sqlite3.OperationalError):
642 con.execute("create table foo(a, b);")
643
644 _sqlite3.enable_callback_tracebacks(True)
645 unraisables = []
646 def _hook(u):
647 unraisables.append(u)
648 old_hook = sys.unraisablehook
649 sys.unraisablehook = _hook
650 try:
651 with pytest.raises(_sqlite3.OperationalError) as e:
652 con.execute("create table foo(a, b);")
653 print(e)
654 finally:
655 _sqlite3.enable_callback_tracebacks(False)
656 sys.unraisablehook = old_hook
657 assert len(unraisables) > 0
658 cm = unraisables[-1]
659 assert cm.exc_type == ZeroDivisionError
660
661 def test_adapt_three_args():
662 assert _sqlite3.adapt(print, alt=123) == 123
663 with pytest.raises(_sqlite3.ProgrammingError):
664 _sqlite3.adapt(print)
665
666 def test_bad_conform(con):
667 class BadConform:
668 def __conform__(self, protocol):
669 raise TypeError
670 val = BadConform()
671 con.execute("create table test(foo)")
672 with pytest.raises(_sqlite3.ProgrammingError) as info:
673 con.execute("insert into test(foo) values (?)", (val,))
674 assert 'BadConform' in str(info.value)
675
676 def test_collation_unicode(con):
677 con.create_collation('ä', lambda *args: None)
678
679 def test_function_raises_memory_error(con):
680 def mem():
681 raise MemoryError()
682 con.create_function("mem", 0, mem)
683 with pytest.raises(MemoryError):
684 cur = con.execute("select mem()")
685
686 def test_function_raises_overflow_error(con):
687 def ovf():
688 raise OverflowError()
689 con.create_function("ovf", 0, ovf)
690 with pytest.raises(_sqlite3.DataError):
691 cur = con.execute("select ovf()")
692
693 def test_window_function(con):
694 class WindowSumInt:
695 def __init__(self):
696 self.count = 0
697
698 def step(self, value):
699 self.count += value
700
701 def value(self):
702 return self.count
703
704 def inverse(self, value):
705 self.count -= value
706
707 def finalize(self):
708 return self.count
709
710 con.create_window_function('sumint', 1, WindowSumInt)
711 con.execute("create table test(x, y)")
712 values = [
713 ("a", 4),
714 ("b", 5),
715 ("c", 3),
716 ("d", 8),
717 ("e", 1),
718 ]
719 con.executemany("insert into test values(?, ?)", values)
720 query = """
721 select x, sumint(y) over (
722 order by x rows between 1 preceding and 1 following
723 ) as sum_y
724 from test order by x
725 """
726 res = con.execute(query)
727 assert list(res) == [
728 ("a", 9),
729 ("b", 12),
730 ("c", 16),
731 ("d", 12),
732 ("e", 9),
733 ]
734
735 def test_query_limit(con):
736 con.setlimit(_sqlite3.SQLITE_LIMIT_SQL_LENGTH, 100)
737 limit = con.getlimit(_sqlite3.SQLITE_LIMIT_SQL_LENGTH)
738 with pytest.raises(_sqlite3.DataError) as info:
739 con.execute('select 1'.ljust(limit + 1))
740 assert "query string is too large" in str(info.value)
741 with pytest.raises(_sqlite3.DataError) as info:
742 con.executescript('select 1'.ljust(limit + 1))
743 assert "query string is too large" in str(info.value)
744
745 @pytest.mark.skipif(
746 not hasattr(_sqlite3.Connection, 'serialize'),
747 reason='sqlite3 version too old for serialize')
748 def test_serialize(con):
749 with con:
750 con.execute("create table t(t)")
751 data = con.serialize()
752 assert len(data) == 8192
753
754 # Remove test table, verify that it was removed.
755 with con:
756 con.execute("drop table t")
757 with pytest.raises(_sqlite3.OperationalError):
758 con.execute("select t from t")
759
760 # Deserialize and verify that test table is restored.
761 con.deserialize(data)
762 con.execute("select t from t")
763
764 class TestBlob:
765 def test_simple(self, con):
766 con.execute("create table test(b blob)")
767 data = b"this blob data string is exactly fifty bytes long!"
768 con.execute("insert into test(b) values (?)", (data, ))
769 with con.blobopen("test", "b", 1) as blob:
770 assert blob.read(len(data)) == data
771
772 def test_write(self, con):
773 con.execute("create table test(b blob)")
774 data = b"this blob data string is exactly fifty bytes long!"
775 con.execute("insert into test(b) values (?)", (data, ))
776 with con.blobopen("test", "b", 1) as blob:
777 blob.write(b"some new data")
778 assert blob.tell() == len(b"some new data")
779 with con.blobopen("test", "b", 1) as blob:
780 assert blob.read() == b'some new dataa string is exactly fifty bytes long!'
781
782 def test_seek(self, con):
783 con.execute("create table test(b blob)")
784 data = b"this blob data string is exactly fifty bytes long!"
785 con.execute("insert into test(b) values (?)", (data, ))
786 with con.blobopen("test", "b", 1) as blob:
787 blob.write(b"some new data")
788 blob.seek(0)
789 assert blob.read() == b'some new dataa string is exactly fifty bytes long!'
790
791 def test_seek_to_end(self, con):
792 con.execute("create table test(b blob)")
793 data = b"this blob data string is exactly fifty bytes long!"
794 con.execute("insert into test(b) values (?)", (data, ))
795 with con.blobopen("test", "b", 1) as blob:
796 blob.seek(len(data))
797 assert blob.read() == b''
798
799 def test_getitem(self, con):
800 con.execute("create table test(b blob)")
801 data = b"this blob data string is exactly fifty bytes long!"
802 con.execute("insert into test(b) values (?)", (data, ))
803 with con.blobopen("test", "b", 1) as blob:
804 assert blob[0] == ord('t')
805 assert blob[:2] == b'th'
806 assert blob[::2] == data[::2]
807
808 def test_setitem(self, con):
809 con.execute("create table test(b blob)")
810 data = b"this blob data string is exactly fifty bytes long!"
811 con.execute("insert into test(b) values (?)", (data, ))
812 with con.blobopen("test", "b", 1) as blob:
813 blob[0] = 14
814 assert blob[0] == 14
815 blob[:len(b"some new data")] = b"some new data"
816 assert blob.tell() == 0
817 with con.blobopen("test", "b", 1) as blob:
818 assert blob.read() == b'some new dataa string is exactly fifty bytes long!'
819 with pytest.raises(IndexError):
820 with con.blobopen("test", "b", 1) as blob:
821 blob[-1999] = 14
822
823 def test_setitem_stride(self, con):
824 con.execute("create table test(b blob)")
825 data = b"this blob data string is exactly fifty bytes long!"
826 con.execute("insert into test(b) values (?)", (data, ))
827 with con.blobopen("test", "b", 1) as blob:
828 blob[0] = 14
829 assert blob[0] == 14
830 blob[:len(b"some new data")*2:2] = b"some new data"
831 assert blob.tell() == 0
832 expected = bytearray(data)
833 expected[:len(b"some new data")*2:2] = b"some new data"
834 assert blob[:] == expected
835
836
837 def test_threadsafe():
838 assert _sqlite3.threadsafety in {0, 1, 3}
839
840 def test_sql_lstrip_comments():
841 strip = _sqlite3._sql_lstrip_comments
842 assert strip(' *not a comment') == '*not a comment'
843 assert strip(' -*not a comment') == '-*not a comment'
844 assert strip(' -- foo bar') == ''
845 assert strip(' --') == ''
846 assert strip(' -\n- select 2') == '-\n- select 2'
847 assert strip(' /') == '/'
848 assert strip(' /* */ a') == 'a'
849 assert strip(' /*') == ''
850 assert strip(' // c++ comments are not allowed') == '// c++ comments are not allowed'
851 assert strip(' select 2') == 'select 2'
852 assert strip('\n -- comment\n select 2\n ') == 'select 2\n '
853 assert strip('\n ') == ''
854 assert strip('\n\n /*\n foo\n */\n ') == ''
855
856 def test_weird_reinit(con):
857 # not quite sure why that's useful, but oh well
858 with pytest.raises(_sqlite3.OperationalError):
859 con.__init__('hopefull/does/not/exist/in/this/directory/äöúß')
860 with pytest.raises(_sqlite3.ProgrammingError):
861 con.execute('select 1')
862 con.__init__(':memory:')
863
864 def test_module():
865 assert _sqlite3.DataError.__module__ == "sqlite3"